I have a nested dictionary. Sometimes it contains more than two attachments. How can I loop through the dictionary to get the following values in the variables ?
dict = {'result': [{'a1': 'one', 'a2': 'two', 'a3': '2'},
{'b1': 'three', 'b2': 'one', 'b3': '5'}]}
res1 = one
res2 = two
res3 = 2
res1 = three
res2 = one
res3 = 5
CodePudding user response:
If you want to store each value in different variable then I would suggest to append those values in a list.
The code to access those values are:
dictt = {'result': [{'a1': 'one', 'a2': 'two', 'a3': '2'},
{'b1': 'three', 'b2': 'one', 'b3': '5'}]}
for key, value in dictt.items() :
for i in range(2):
for item in value[i].values():
print(item)
The ouptut of this is:
one
two
2
three
one
5
CodePudding user response:
dict1 = {'result': [{'a1': 'one', 'a2': 'two', 'a3': '2'},{'b1': 'three', 'b2': 'one', 'b3': '5'}]}
for j in dict1['result']:
print([(j[k]) for k in j])
please don't give dict as dictionary name. output:
['one', 'two', '2']
['three', 'one', '5']
to assign the values, refer this code:
dict1 = {'result': [{'a1': 'one', 'a2': 'two', 'a3': '2'},{'b1': 'three', 'b2': 'one', 'b3': '5'}]}
l=[]
l1={}
for j in dict1['result']:
s=[(j[k]) for k in j]
l.append(s)
for z in range(3):
key=str("res" str(z))
l1[key]=[l[0][z], l[1][z]]
print(l1)
you will get this as output:
{'res0': ['one', 'three'], 'res1': ['two', 'one'], 'res2': ['2', '5']}