简体   繁体   English

在字典中查找特定的键值对

[英]Find specific key-value pairs in a dictionary

my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],4: ['Bill', 'Gates', 72], 5: ['Normani', 'Kordei', 24]}

I have that dictionary with a list as values and I'm trying to access say the age (index 2 in the list) of key 3 when found.我有那个字典,其中有一个列表作为值,我试图在找到时访问说键 3 的年龄(列表中的索引 2)。 I tried this code我试过这段代码

def record(num):
    my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
               4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
    for k, v in my_dict.items():
        fname = v[0]
        lname = v[1]
        age = v[2]
        if my_dict.get(num) is None:
            print('Not found')
        else:
            print(num, age, 'Found')

record(3) # Call function

I want something like if I call the function with record(3) I just get the age corresponding to that key like this:我想要类似的东西,如果我用记录(3)调用 function 我只是得到与该键对应的年龄,如下所示:

3 56 Found

Currently I get:目前我得到:

3 38 Found
3 45 Found
3 56 Found
3 72 Found
3 24 Found

You don't need to use a loop, you can just index directly into the dictionary.您不需要使用循环,您可以直接索引到字典中。

def record(num):
    my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
               4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
    if num in my_dict:
        print(num, my_dict[num][2], "Found")
    else:
        print("Not found")

or use try-except to handle the "not found" case (which some may argue is more "Pythonic"):或使用 try-except 来处理“未找到”的情况(有些人可能认为这更“Pythonic”):

def record(num):
    my_dict = {1: ['Serena', 'Williams', 38],2: ['Bradley', 'Cooper', 45],3: ['Wendy', 'Williams', 56],
               4: ['Bill', 'Gates', 72], 5:['Normani', 'Kordei', 24]}
    try:
        print(num, my_dict[num][2], "Found")
    except KeyError:
        print("Not found")

As noted in SuperStormer's answer , you should be directly accessing the record for num by invoking the key on the directory.SuperStormer 的回答中所述,您应该通过调用目录上的键直接访问num的记录。 However using the iteration process you do, the correct item to check is whether k matches the desired key num .但是,使用您执行的迭代过程,要检查的正确项目是k是否与所需的键num匹配。

Note this approach is not recommended - this is just a clean-up of your method:请注意,不建议使用这种方法 - 这只是对您的方法的清理:

my_dict = {1: ['Serena', 'Williams', 38], 2: ['Bradley', 'Cooper', 45],
        3: ['Wendy', 'Williams', 56], 4: ['Bill', 'Gates', 72], 
        5:['Normani', 'Kordei', 24]}

def record(num):
    for k, v in my_dict.items():
        fname, lname, age = v
        if k == num:
            print(num, age, 'Found')
            return
    print (num, "Not found")  

for a in range(7):  # Call function repeatedly to check cases
    record(a)

The output from the seven calls to record above is:上面七个record调用中的 output 是:

0 Not found
1 38 Found
2 45 Found
3 56 Found
4 72 Found
5 24 Found
6 Not found

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM