python dictionary keys - python

I'm having a bit of a problem, don't even know if this is doable. I have a number of launchers that each have a interface defined with the expected inputs. The input values come as a dictionary. For example:
dict_key = str(req_input[0]['name'])
data = dict(dict_key = value)
Now req_input[0]['name'] is the key I would like to insert into the dictionary. Now I know what I'm doint here only creates a dictionary of the form {'dict_key' : value} but I was wondering if it is possible to create the dicionary as to be the form {'Actual value of dict_key' : value}
Regards,
Bogdan

The best way to do this is simply using the dict literal {}:
data = {dict_key: value}
Other ways would be
data = dict({dict_key: value})
or
data = dict()
data[dict_key] = value
but these are longer so stay with the first one.

Another way is:
data = {}
data[req_input[0]['name']] = value
This way you can add multiple values to the same dictionary, or loop through req_input if you have multiple parameters there, i.e.:
data = {}
for input in req_input:
data[input['name']] = value

Related

How can I search for a specific key in a dictionary in Python?

So I got this dictionary from a csv file and I would like to look for a specific key inside this dictionary (actually the og idea was to search for said key in the csv file and then make a dictionary from that key down) but I don't really know how to do it.
So far I got:
df = pd.read_csv('data.csv')
dict = df.to_dict(orient='dict')
for index, line in enumerate(dict):
if "Wavelength [nm]" in line:
print(index)
The idea is to know the index of "Wavelength".
If you want the value of a key without knowing whether it's in the dict, often the most natural way is
value = dict.get( key, defaultvalue)
defaultvalue is what you would set value to in your code once you had established that the key is not present. Often, None, or an empty list or tuple.
If you just waht to check whether the key is present without accessing the value, use
if key in dict:
# do stuff
you can use:
if key in dict:
print(key,dict[key])

How to reset value of multiple dictionaries elegantly in python

I am working on a code which pulls data from database and based on the different type of tables , store the data in dictionary for further usage.
This code handles around 20-30 different table so there are 20-30 dictionaries and few lists which I have defined as class variables for further usage in code.
for example.
class ImplVars(object):
#dictionary capturing data from Asset-Feed table
general_feed_dict = {}
ports_feed_dict = {}
vulns_feed_dict = {}
app_list = []
...
I want to clear these dictionaries before I add data in it.
Easiest or common way is to use clear() function but this code is repeatable as I will have to write for each dict.
Another option I am exploring is with using dir() function but its returning variable names as string.
Is there any elegant method which will allow me to fetch all these class variables and clear them ?
You can use introspection as you suggest:
for d in filter(dict.__instancecheck__, ImplVars.__dict__.values()):
d.clear()
Or less cryptic, covering lists and dicts:
for obj in ImplVars.__dict__.values():
if isinstance(obj, (list, dict)):
obj.clear()
But I would recommend you choose a bit of a different data structure so you can be more explicit:
class ImplVars(object):
data_dicts = {
"general_feed_dict": {},
"ports_feed_dict": {},
"vulns_feed_dict": {},
}
Now you can explicitly loop over ImplVars.data_dicts.values and still have other class variables that you may not want to clear.
code:
a_dict = {1:2}
b_dict = {2:4}
c_list = [3,6]
vars_copy = vars().copy()
for variable, value in vars_copy.items():
if variable.endswith("_dict"):
vars()[variable] = {}
elif variable.endswith("_list"):
vars()[variable] = []
print(a_dict)
print(b_dict)
print(c_list)
result:
{}
{}
[]
Maybe one of the easier kinds of implementation would be to create a list of dictionaries and lists you want to clear and later make the loop clear them all.
d = [general_feed_dict, ports_feed_dict, vulns_feed_dict, app_list]
for element in d:
element.clear()
You could also use list comprehension for that.

How can I get the key value pair to create a dictionary from a nested dictionary?

I have a dictionary which looks as shown below. Now I need to get the key its corresponding path together so as to use it further to identify its slot number based on the key. How can I achieve that?
I tried an approach but it is giving me key error.
What you need can easily be implemented as:
>>> {key: value["mpath"] for key, value in multipath.items()}
{'/dev/sdh': '/dev/mapper/mpathk', '/dev/sdi': '/dev/mapper/mpathk',
'/dev/sdg': '/dev/mapper/mpathj', '/dev/sdf': '/dev/mapper/mpathj',
'/dev/sdd': '/dev/mapper/mpathi', '/dev/sde': '/dev/mapper/mpathi',
'/dev/sdb': '/dev/mapper/mpathh', '/dev/sdc': '/dev/mapper/mpathh',
'/dev/sdj': '/dev/mapper/mpathg', '/dev/sdk': '/dev/mapper/mpathg'}
Great one line answer by #Selcuk using dictionary comprehension.
An elaborated one along the same line would be:
mpath_dict = {}
for sd, mpath in multipath.items():
mpath_dict[sd] = mpath['mpath']
print(mpath_dict)
Since every value item of "mpath" dictionary is a dictionary itself, you can retrieve values from it as you would do it in a dictionary.

Retrieve values from both nested dictionaries within a list

i'm using an api call in python 3.7 which returns json data.
result = (someapicall)
the data returned appears to be in the form of two nested dictionaries within a list, i.e.
[{name:foo, firmware:boo}{name:foo, firmware:bar}]
i would like to retrieve the value of the key "name" from the first dictionary and also the value of key "firmware" from both dictionaries and store in a new dictionary in the following format.
{foo:(boo,bar)}
so far i've managed to retrieve the value of both the first "name" and the first "firmware" and store in a dictionary using the following.
dict1={}
for i in result:
dict1[(i["networkId"])] = (i['firmware'])
i've tried.
d7[(a["networkId"])] = (a['firmware'],(a['firmware']))
but as expected the above just seems to return the same firmware twice.
can anyone help achive the desired result above
you can use defaultdict to accumulate values in a list, like this:
from collections import defaultdict
result = [{'name':'foo', 'firmware':'boo'},{'name':'foo', 'firmware':'bar'}]
# create a dict with a default of empty list for non existing keys
dict1=defaultdict(list)
# iterate and add firmwares of same name to list
for i in result:
dict1[i['name']].append(i['firmware'])
# reformat to regular dict with tuples
final = {k:tuple(v) for k,v in dict1.items()}
print(final)
Output:
{'foo': ('boo', 'bar')}

How to make a list of dicts with nested dicts

I am not sure if thats what i really want but i want this structure basically,
-document
-pattern_key
-start_position
-end_position
right now i have this
dictionary[document] = {"pattern_key":key, "startPos":index_start, "endPos": index_end}
but i want to nest startPos, endPos under pattern key
Also how can i update this, to add a new entry of pattern_key, startPos, endPos, under same document?
with this you can updates values of the keys
for x in dict.keys():
if 'pattern_key' in x:
dict[x]= 'new value'
if 'endPost'...
.....
print dict
>>> should have new values
for add new entrys:
old = {}
old['keyxD'] = [9999]
new = {}
new['newnewnew'] = ['supernewvalue']
new.update(old)
print new
>>>{'newnewnew': ['supernewvalue'], 'keyxD': [9999]}
Not sure what you exactly want, but you can try this:
document = {'pattern_key' : {}}
This created an object document which is a dictionary, where the key is a string (pattern_key) and the value is another dictionary. Now, to add new entries to the value of the dictionary (which is another dictionary) you just add your values:
document['pattern_key']['start_position'] = 1
document['pattern_key']['end_position'] = 10
Afterwards, you can enter either case with document['pattern_key']['start_position'] = 2 and this will change the start position to 2.
Hope this helps

Categories