Reputation: 29
What I want the code below to achieve is that for which ever dictionary who has smaller value of temporary key, add an item in that dictionary with key "permanent" and value same as the value for the temporary key.
Variable="a"
a_list={'a': {'c': '2', 'b': '1'}, 'c': {'a': '2', 'b': '3'}, 'b': {'a': '1', 'c': '3'}}
a_list[Variable]["permanent"]="1"
for item in a_list[Variable].keys():
try:
if a_list[Variable][item]!=0:
a_list[item]["temporary"]=a_list[Variable][item]
except KeyError:
pass
for item in a_list.keys():
if "permanent" in a_list[item].keys():
del a_list[item]
print a_list
the output now is
{'c': {'a': '2', 'b': '3', 'temporary': '2'}, 'b': {'a': '1', 'c': '3', 'temporary': '1'}}
But after adding an statement I want the output to be
{'c': {'a': '2', 'b': '3', 'temporary': '2'}, 'b': {'a': '1', 'c': '3', 'temporary': '1', 'permanent': '1'}}
I don't know how to achieve this by comparing the two temporary keys in the two dictionaries. Would very much appreciate any help!
Upvotes: 1
Views: 74
Reputation: 15320
The min
function will iterate over a list. If given a special key=
named parameter, it will use the one-argument function passed in as the key=
function to extract the value to use for comparison purposes.
You show dictionaries using only strings containing digits. The maximum string is therefore 'A' (asciibetically later than a digit). So:
max_value = 'A'
min_temp = min(a_list.keys(), key= lambda k: a_list[k].get('temporary', max_value))
At this point, min_temp
has the first key in a_list
that has the lowest value for sub-dict key 'temporary', or if none had that subkey, the first key returned by keys()
(with a defaulted value of max_value
). So let's double-check that it was a valid match:
if 'temporary' in a_list[min_temp]:
a_list[min_temp]['permanent'] = a_list[min_temp]['permanent']
Upvotes: 1