Home > database >  How to choose certain dictionary keys ,and then move the whole dictionary to a separate list
How to choose certain dictionary keys ,and then move the whole dictionary to a separate list

Time:11-15

I have a list of dictionaries

[{country : UK, age : no20, mode : 1}, {country : USA, age: 25, mode : 0}, 
 {country : France, age : 23, mode : 1}]

I would like to take the two dictionaries with only 'mode : 0' and then store them in a separate list / dictionary

Any help is appreciated

Thanks :)

CodePudding user response:

So first your example of a list of dict is wrong most likely. Keys and some values are string and so you must quote them.

Otherwise this does what you want:

lst = [{'country' : 'UK', 'age' : 20, 'mode' : 1}, {'country' : 'USA', 'age': 25, 'mode' : 0}, {'country' : 'France', 'age' : 23, 'mode' : 1}]

print([x for x in lst if x['mode'] == 0])
  • Related