0

I have a list of dictionaries. e.g:

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"} ]

1
  • What have you tried? Please be sure to read the About for StackOverflow, and the guide to asking good questions. stackoverflow.com/questions/how-to-ask | stackoverflow.com/about Commented Aug 15, 2013 at 1:10

3 Answers 3

3

I think a list comprehension would work well here:

[innerdict["key3"] for innerdict in list] 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

key3 contains not a string called 'dict1' but contains a dictionary called dict1. did you see any quotes around dict1 in the question?
If I write dict1 without quotes, then it won't compile, because it's unhashable and you can't put it in a set. So either way, the sample code in the question won't work. Anyway, I removed that part of my answer, until OP posts some code that makes sense
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.