【问题标题】:Search dictionary by dictionary按字典搜索字典
【发布时间】:2020-10-05 16:52:34
【问题描述】:

我有两本词典:

v = {'name': ['Peter', 'Paul', 'Mary'], 'city': ['London', 'Rome', 'NY'], 'country': ['GB', 'I', 'USA'], 'age': ['30', '35', '45']}

d = {'city': 'Rome', 'country': 'I', 'age': 35}

如果我在 v 中搜索来自 d 的确切值,我希望返回 Paul

我是否必须通过所有可能性“嵌套循环”,或者是否有类似的简单方法

if all of d anywhere in v.rows:
    print(v[name])

【问题讨论】:

  • 你为什么使用列表字典而不是字典列表?
  • 您当前的数据结构不适合这种搜索。

标签: python dictionary search find


【解决方案1】:

循环遍历name 元素,并将其他列表的对应元素与d 值进行比较。

found = None
for i, name in v['name']:
    if all(v[key][i] == val for key, val in d):
        found = name

【讨论】:

    【解决方案2】:

    假设你的长度相同,

    for i in range(len(v['name'])):
        #compare all the other details and print the name
        if d['city']==v['city'][i] and d['country']==v['country'][i] \
            and d['age']==v['age'][i]:
            print(v['name'][i])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 2012-02-09
      • 2019-08-02
      • 1970-01-01
      • 2011-07-07
      • 2011-08-20
      相关资源
      最近更新 更多