简体   繁体   中英

How to remove values from a dictionary?

I want to delete chosen values of a python dictionary.

For instance in the following python dictionary I want to remove pair numbers for each key,

year_dict = {2010: [1], 2009: [4,7,5,8,10], 1989: [5,6,7,15]}

I want to obtain

year_dict = {2010: [1], 2009: [7,5], 1989: [5,7,15]}

From your example, it looks like you want to remove even numbers from the dictionary values. To do this, you can iterate over the items of your dictionary, and filter out even numbers using a list comprehension.

>>> {k: [i for i in v if i%2==1] for k, v in year_dict.items()}
{2010: [1], 2009: [7, 5], 1989: [5, 7, 15]}

As Cory said, you can iterate over the items which gives you pair of key and corresponding value. You can also iterate only using.keys() and then getting the corresponding value using list comprehension:

year_dict = {key: [val for val in year_dict[key] if val%2==1] for key in year_dict.keys()}

you can also use the filter function. filter() function in Python takes in a function and a list as arguments. This offers an elegant way to filter out all the elements of a sequence “sequence”, for which the function returns True .

>>>{k: list(filter(lambda x: (x%2 != 0) , v)) for k, v in year_dict.items()}
{2010: [1], 2009: [7, 5], 1989: [5, 7, 15]}

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