-1

How to compare and replace keys inside nested dictionaries according to what user inputs

user3236912
  • 9
  • 1
  • 6

1 Answers1

3
dic = {'Sally':['1346','A','April', {'1346': ('week', 6)}],
       'Annie': ['1347', 'A', 'April', {'1346': ('week', 5)}],
       'Marie': ['0', 'Absent', 'Fall', {}]}

for value in dic.values():
    for element in value:
         if isinstance(element, dict) and '1346' in element:
             element['1346'] = ('month',6)

if this were Python 2, I would use dic.itervalues() instead of dic.values().

And here's the results:

>>> import pprint
>>> pprint.pprint(dic)
{'Annie': ['1347', 'A', 'April', {'1346': ('month', 6)}],
 'Marie': ['0', 'Absent', 'Fall', {}],
 'Sally': ['1346', 'A', 'April', {'1346': ('month', 6)}]}
Russia Must Remove Putin
  • 374,368
  • 89
  • 403
  • 331
  • Can you tell me how can I check for condition just before replacing. – user3236912 Jan 26 '14 at 07:32
  • Forexample, just before replacing I want to check if 2nd value of tuple associated with a key is less than 9 only then replace otherwise delete the whole key and assoicated value from nested dictionary – user3236912 Jan 26 '14 at 07:34
  • So to do that, instead of immediately assigning the element dict value to the key, you'd do that check on the element dict. e.g. ``if element[1346][1] > 9: del element['1346']``, else: do the assignment. – Russia Must Remove Putin Jan 26 '14 at 07:40
  • Ok, I will post shortly. And in above solution is it 1346 or '1346'?e.g.if element[1346][1] > 9: del element['1346'] – user3236912 Jan 26 '14 at 07:46
  • It's fairly standard to use integers and not string representations of integers, but that's up to you. Yeah, I used an integer and that should have been a string, '1346'. – Russia Must Remove Putin Jan 26 '14 at 07:52