按字典搜索字典

时间:2020-10-05 16:52:34

标签: python dictionary search find

我有两个字典:

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

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

如果我搜索Paulv的确切值,我想返回d

我是否必须“嵌套循环”所有可能性,还是有简单的方法

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

2 个答案:

答案 0 :(得分:0)

浏览name元素,然后将其他列表的相应元素与d值进行比较。

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

答案 1 :(得分:0)

假设您的长度相同,

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])