【问题标题】:Check if list with given items is present in dict [duplicate]检查dict中是否存在给定项目的列表[重复]
【发布时间】:2017-02-08 10:54:51
【问题描述】:

我有一个这样的字典和一个列表:

hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']}
temp = ['Cook', 'a']

我想检查temp 是否存在于hey 中。我的代码:

def checkArrayItem(source,target):
    global flag
    flag = True

    for item in source:
        if (item in target):
            continue
        else:
            flag = False
            break
for i,arr in enumerate(hey) :
    if (len(temp) == len(hey[arr])):
        checkArrayItem(temp,hey[arr])
        if (flag):
            print('I got it')
            break

有什么更优雅的方式来做这个检查?

【问题讨论】:

  • 你的意思是你有一个dict和一个list
  • 谢谢,我看到了链接。

标签: python


【解决方案1】:

temp in hey.values()怎么样?

【讨论】:

  • 谢谢,优秀的回答
  • @RelaxZeroC:不客气。
【解决方案2】:

只需使用sets 完全与容器进行比较:

In [40]: hey = {'2': ['Drink', 'c', 'd'], '1': ['Cook', 'a']}

In [41]: temp = {'Cook', 'a'}
# This will give you the keys within your dictionary that their values are equal to tamp
In [42]: [k for k, v in hey.items() if set(v) == temp]
Out[42]: ['1']

【讨论】:

  • 谢谢,很好用。
猜你喜欢
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 2018-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多