简体   繁体   中英

Get a list from the dictionary key in a list of dictionaries

I have a list of dictionaries. eg:

list = [ {list1}, {list2}, .... ]

One of the key-value pair in each dictionary is another dictionary. Ex

list1 = { "key1":"val11", "key2":"val12", "key3":{"inkey11":"inval11","inkey12":"inval12"} }
list2 = { "key1":"val21", "key2":"val22", "key3":{"inkey21":"inval21","inkey22":"inval22"} }

I was thinking of getting all values of key3 in the all the dictionaries into a list. Is it possible to access them directly (something like list[]["key3"] ) or do we need to iterate through all elements to form the list?

I have tried

requiredlist = list [ ] ["key3"].

But it doesn't work. The final outcome I wanted is

requiredlist = [ {"inkey11":"inval11","inkey12":"inval12"}, {"inkey21":"inval21","inkey22":"inval22"} ]

我认为列表理解在这里很有效:

[innerdict["key3"] for innerdict in list]

Try this:

list1["key3"]

Notice that list1 and list2 as you defined them are dictionaries, not lists - and the value of "key3" is a set , not a list. You're confounding {} with [] , they have different meanings.

To access an element is a dictionary you must do the following:

dict_name[key_name] #in this case: list1[key3]

Try this:

newlist = []
list = [{ "key1":"val11", "key2":"val12", "key3":{dict1} },{ "key1":"val21", "key2":"val22", "key3":{dict1} }]
for innerdict in list:
    newlist += list(innerdict["key3"]) 
print newlist #This will give all the values of key3 in all the dictionaries

if dict1 in the lists is a set then the above example will work good, but if it is a dictionary then it will give a list but ONLY the keys will be included so if it is a dictionary try this:

newlist = []
list = [{ "key1":"val11", "key2":"val12", "key3":{dict1} },{ "key1":"val21", "key2":"val22", "key3":{dict1} }]
for innerdict in list:
    newlist.append(innerdict["key3"]) 
print newlist #This will give all the values of key3 in all the dictionaries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM