Skip to content Skip to sidebar Skip to footer

Iterate List Of Dictionary And Append Python

I have a List of dictionaries (a) and i'm trying to iterate through the dictionaries search for a specific value and if the dictionary has that value add that dictionary to a new c

Solution 1:

The data structure you have is not quite convenient for this use case/query. If you cannot change the data structure, here is a naive solution:

newList = [d for d in a if "blue" in d.values()]

Note that if "blue" in d.values() lookup is O(n) which is what you should ideally try to avoid when performing in lookups.


A more suitable data structure in this case would be the one that has the key and values in the inner dictionaries swapped:

a = [{"green": "one", "blue": "two", "red": "three"},
     {"blue": "two":, "green": "four", "yellow": "five"},
     {"blue": "two", "white": "six", "black": "seven"}]

In this case, you would look into the dictionaries by key which would be O(1):

newList = [d for d in a if "blue" in d]

Solution 2:

I'm not entirely sure what you are trying, but I modified your example as little as possible to achieve your goal:

ewList = []
a = [{"one": "green", "two": "blue", "three": "red"},
     {"two": "blue", "four" : "green", "five" : "yellow"},
     {"two": "yellow", "six": "white", "seven" : "black"}]

for d in a:
    if"yellow" in d.values():
        ewList.append(d)

print ewList

Output:

[{'four': 'green', 'five': 'yellow', 'two': 'blue'}, {'seven': 'black', 'six': 'white', 'two': 'yellow'}]

Post a Comment for "Iterate List Of Dictionary And Append Python"