Home > Mobile >  Getting error accessing two dictionaries items in "for loop" in python
Getting error accessing two dictionaries items in "for loop" in python

Time:06-19

I am working on a python project in which I have 2 nested dictionaries, and I want to change the value of dict2 dictionary with the dict1. However, the for loop is not able to access both dictionaries. It is taking one dict at a time.

How we can parse both in for loop?

for columnName,columnData in dict2.items(),dict1.items():
    for key in columnData:
        dict2[columnName][key]=dict1[columnName][key]

Error Picture:

Error Picture

dict1:

'Please select your father/guardian monthly Income from these options.': {
  'Between 25k to 50k': 1,
  'Between 75k to 100k': 1,
  'Between 50k to 75k': 1,
  'Between 100k to 150k': 1,
  'Between 150k to 200k': 1,
  'Between 200k to 250k': 1,
  "Father don't do any job": 1,
  'Between 10k to 25k': 1,
  'Between 250k to 300k': 1,
  'More than 1 million': 1,
  'Between 400k to 450k': 1,
  'Between 300k to 350k': 1,
  'Between 350k to 400k': 1,
  'Between 450k to 500k': 1,
  'Between 500k to 550k': 1,
  'Between 550k to 600k': 1,
  'Between 600k to 650k': 1,
  'Less than 10k': 1,
  'Between 750k to 800k': 1
},

dict2:

'Please select your father/guardian monthly Income from these options.': {6: 110,
  1: 94,
  2: 89,
  3: 75,
  4: 47,
  7: 26,
  10: 26,
  8: 22,
  5: 13,
  9: 10,
  11: 5,
  12: 4,
  17: 4,
  15: 3,
  19: 3,
  13: 2,
  14: 2,
  16: 2,
  18: 1},

I want the output like this

'Please select your father/guardian monthly Income from these options.':{
1:'Between 25k to 50k',
2:'Between 75k to 100k',
3:'Between 50k to 75k',
4:'Between 100k to 150k',
7:'Between 150k to 200k',
10:'Between 200k to 250k',
8:'Father don't do any job',
5:'Between 10k to 25k',
.....}

CodePudding user response:

for key1, key2 in zip(dict1.keys(), dict2.keys()):
    for sub_key1, sub_key2 in zip(dict1[key1].keys(), dict2[key2].keys()):
        dict2[key2][sub_key2] = sub_key1

CodePudding user response:

You could either add the two lists together and loop through that, or have another loop on the outside like this for dict in [dict1.keys(),dict2.keys()]:

  • Related