I have a dictionary whose keys and values are updated from internet. This dictionary keeps changing the position and number of its keys/variables on every update (for some reason) but the names of keys and formats of values remain the same. Initially, I converted its keys and values to different arrays and was storing their values to database by following their array locaton, but after I discovered its variability, its no more possible to do it the same way I was doing, since the len(dictionary) keeps changing. The dictionary items are fetched from a url on every update, which sometime gives me 31 items (each item is key:value) and sometime gives me 3, 29 , 28 or even 27 items in the dictionary. So, I have made a generalization about some ‘always-there’ items and now I want to extract them on every update, but not according to their order, but according to their keys. Its more like: I need to search for specific keywords in the dictionary and to save their corresponding values to the variables. For instance, on one update it’s keys are:
>>> len(dict.keys())
>>> 30
on another update:
>>> len(dict.keys())
>>> 26
This shows the number of items in the dictionary keeps variating. However, I have noted a list of some obligatory keys (that I am mentioning below) which are always there so I just need to look for them whenever the thing is updated. In more precise terms, I need a way to extract specific keys (probably by searching) and their corresponding values from the dictionary and to save both them to different variables so that I can save them to database. The keys to be searched are:
- temp_f
- relative_humidity
- wind_dir
- pressure_mb
- location
Thanks.
If I understood your problem well, you don’t need to maintain the order of keys/values in your dictionary and you just want to strip your dictionary from unwanted keys and rename the keys you are interested in. Your concern is that some keys might also be missing. I would solve it in this way.