根据字典中的键值检查列表中的值,Python
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据字典中的键值检查列表中的值,Python相关的知识,希望对你有一定的参考价值。
我有两个数据源,一个是列表,另一个是字典的列表,我的数据看起来像下面。
need_placeholder = ['1200', '1300', '1400']
ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"},
{"Name": "C", "ID": "1400"}]
我需要检查是否 need_placeholders
项目等于 ID
值从 ad_dict
. 这是我的脚本。
for item in need_placeholder:
adpoint_key = item
for index, my_dict in enumerate(ad_dict):
if my_dict["ID"] == adpoint_key:
continue
else:
print(f'No key exists for {adpoint_key}')
输出是:
No key exists for 1200 No key exists for 1200 No key exists for 1200 No key exists for 1300 No key exists for 1300 No key exists for 1300
我想要的输出是:
No key exists for 1200 No key exists for 1300
我怎样才能在不循环浏览字典或列表的情况下比较这些值呢?
答案
你可以试试这个。
>>> need_placeholder = ['1200', '1300', '1400']
>>> ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"},
{"Name": "C", "ID": "1400"}]
>>> keys={d['ID'] for d in ad_dict} # Set of all unique ID values
>>> [key for key in need_placeholder if not key in keys]
# ['1200', '1300']
你可以使用 itertools.filterfalse
list(filterfalse(lambda x:x in keys, need_placeholder))
# ['1200', '1300']
如果你不在乎秩序
set(need_placeholder)-keys
# {'1300', '1200'}
使用 all
>>> for key in need_placeholder:
... if all(key != d['ID'] for d in ad_dict):
... print(f'No key exists for {key}')
...
No key exists for 1200
No key exists for 1300
使用 for-else
>>> for key in need_placeholder:
... for d in ad_dict:
... if key==d['ID']:
... break
... else:
... print(f'No key {key}')
...
No key 1200
No key 1300
另一答案
你有你的 else
在循环中的错误位置。那个内循环每出一个都要运行几次。你可以完全避免那个循环,如果你拉出你的 ID
先将值放入一个集合中。
need_placeholder = ['1200', '1300', '1400']
ad_dict = [{"Name": "A", "ID": "1999"}, {"Name": "B", "ID": "1299"}, {"Name": "C", "ID": "1400"}]
ad_values = set(d['ID'] for d in ad_dict)
for v in need_placeholder:
if v not in ad_values:
print(f'no key exits for {v}')
Prints:
no key exits for 1200
no key exits for 1300
如果顺序并不重要,你可以将整个过程作为一个单一的集合操作来完成。
for v in set(need_placeholder) - ad_values:
print(f'no key exits for {v}')
另一答案
allowed_values = {dic["ID"] for dic in ad_dict}
for item in need_placeholder:
if item not in allowed_values:
print(f'No key exists for {item}')
另一答案
一个快速的方法是使用嵌套的列表理解法
[print('No key for {}'.format(x)) for x in need_placeholder if x not in [y['ID'] for y in ad_dict]]
另一答案
for item in need_placeholder:
adpoint_key = item
duplicate_exist = False # flag that will be update if key exists
for index, my_dict in enumerate(ad_dict):
if my_dict["ID"] == adpoint_key:
duplicate_exist = True # flag is updated as key exists
not duplicate_exist and print(f'No key exists for {adpoint_key}') # for all non duplicate print function is invoked at the end of inner loop
以上是关于根据字典中的键值检查列表中的值,Python的主要内容,如果未能解决你的问题,请参考以下文章
Python面试必考重点之列表,元组和字典第十三关——有哪些数据类型不能作为字典键值的类型/为什么列表和字典类型的值不能作为字典的键值