简体   繁体   中英

Create a new dictionary comparing to a list in python

I have a dictionary. I want to create a new dictionary comparing a list, ( my_list ) of values to my dictionary's values.

My dictionary, code_dict keys and values:

33003282 :['25000', '27800', 'None', '4779'], 
33003283: ['2564', '6264', '78784', '7841', '89564'], 
33003285: ['32723', '8954', '5259', '5225', '25000','04189', '8820', '2166']

I have my_list like this:

my_list = ['27800', '6264', '5225']

Now, I want to compare my list values to Dictionary values and create a new dictionary that has values like this,

33003282 :['25000', 'None', '4779'], 
33003283: ['2564','78784', '7841', '89564'], 
33003285: ['32723', '8954', '5259', '25000','04189', '8820', '2166']

I did the following in comprehension way hoping that I could do like how we do it in lists :

new_dict = {key: value for value in code_dict.items()}.isin([code for code in my_list])

using isin in dictionaries does not work, how can I create a new dictionary?

You can try this:

d = {33003282 :['25000', '27800', 'None', '4779'], 33003283: ['2564', '6264', '78784', '7841', '89564'],33003285: ['32723', '8954', '5259', '5225', '25000','04189', '8820', '2166']}
my_list = ['27800', '6264', '5225']
final_d = {a:[i for i in b if i not in my_list] for a, b in d.items()}

Output:

{33003282: ['25000', 'None', '4779'], 33003283: ['2564', '78784', '7841', '89564'], 33003285: ['32723', '8954', '5259', '25000', '04189', '8820', '2166']}

The output is a dictionary where the values are filtered so that none of its elements exist in my_list

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