Halloween
Halloween

Reputation: 418

Python get the items in a list from a dictionary within a list

I have a list that contains dictionaries. Each dictionary has a list for the value.I have a dictionary that contains a list for the values.

mylist = {'prop3': ['ss']}, {'mvpd': ['asdf', 'wefef']}, {'app_name': ['d']}

I need a way to get the lists inside each dictionary. I will know which key of the dictionary I want to grab the list from.

For example. With the above structure I want to be able to just pull out 'asdf', 'wefef' from the mvpd key.

Upvotes: 0

Views: 567

Answers (1)

Joshua Varghese
Joshua Varghese

Reputation: 5202

Let:

mylist = [{'prop3': ['ss']}, {'mvpd': ['asdf', 'wefef']}, {'app_name': ['d']}]

and the key you require is:

key = 'mvpd'

We'll now check if the key exists in each item of the list:

[i[key] for i in mylist if key in i]

gives:

[['asdf', 'wefef']]

You your list dictionaries have a unique value:

for i in mylist:
    if key in i:
        res = i[key]

but if two dictionaries can have the same key:

res = []
for i in mylist:
    if key in i:
        res.append([key])

Upvotes: 4

Related Questions