Home > Mobile >  How do i access all values of keys inside a list which itself is a value of another dictionary?
How do i access all values of keys inside a list which itself is a value of another dictionary?

Time:04-11

dict = {key1:"value", key2:[{id:"value21", name:"value31" }, {id:"value22",name:"value32"},{id: "899",name:"values"}], key3:"value3"}

I need to extract all the values of name

CodePudding user response:

You can try:

dict = {"key1":"value", "key2":[{"id":"value21", "name":"value31" }, {"id":"value22","name":"value32"},{"id": "899","name":"values"}], "key3":"value3"}

for data in dict["key2"]:
    if "name" in data:
        print(data["name"])

Output

value31
value32
values

CodePudding user response:

First of all the question needed to be formatted correctly as the keys are strings.


# make sure keys are strings
key1 = 'a'
key2 = 'b'
key3 = 'c'
name = 'name'

# make a valid dictionary

d = {key1:"value", 
    key2:[{'id':"value21", name:"value31" }, {'id':"value22",name:"value32"},{'id': "899",name:"values"}],
     key3:"value3"}

# this is a list
result = d[key2]

# inspect list
for i in result:
    if name in i.keys():
        print (i[name])

returns this:

value31
value32
values

CodePudding user response:

  1. dict and id are reserved so I changed them to dct and 'id':
dct = {'key1':"value",'key2':[{'id':"value21", 'name':"value31" },{'id':"value22",'name':"value32"},{'id': "899",'name':"values"}],'key3':"value3"}

I also changed the keys to strings since otherwise python expects a variable name and I think that you want to iterate over the dict w/o knowing the keys in advance.

  1. Iterate over the dict values and extract the names from the nested dicts in list:
all_names = []

for value in dct.values():
    if isinstance(value, list):
        for sub_dct in value:
            try:
                all_names.append(sub_dct['name'])
            except KeyError:
                pass

print(all_names)

CodePudding user response:

if the dict is in given format, the following code can be used

dictor = {'key1':"value", 'key2':[{'id':"value21", 'name':"value31" }, {'id':"value22",'name':"value32"},{'id': "899",'name':"values"}], 'key3':"value3"}

the logic to get the name is:

def GetValues(dictionary):
    name_data = []
    for i in dictor.keys():
        if type(dictor[i]) is list:
            for i in dictor[i]:
                name_data.append(i['name'])
    return name_data

print(GetValues(dictor))

will get the output as

['value31', 'value32', 'values']
  • Related