Retrieve values from both nested dictionaries within a list

56kb :

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

Adam.Er8 :

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')}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386635&siteId=1