简体   繁体   English

如何在python中的字典中遍历列表

[英]How to iterate through a list in a dictionary in python

sampleDict={ “A1”:[“234-234-2234”, [“Brown”, “Bill”] ], “B2”:[“654-564-5564”,[“Jones”,”Jennifer”]] }

I have to check to see it "john" is in the dictionary and print the first and last name of everyone whose phone number begins with "654" 我必须检查字典中是否有"john" ,并打印电话号码以"654"开头的每个人的名字和姓氏

and my code is: 我的代码是:

for i in sampleDict.keys():    
    for key in sampleDict[i]:
        print(key)

and how do i just print the last name in the list : "Brown" 以及如何在列表中打印姓氏:“棕色”

It seems you don't care about the key ? 看来您不在乎key

for values in sampleDict.values():
    lname = values[1][0] # Assuming that last name is always the first element
    fname = values[1][1] # Assuming that first name is always the second element
    # Checking if `name` is in names list
    if 'john' in values[1]:
        # do whatever

In general, you can access the different parts of the dictionary values through list indexing: 通常,您可以通过列表索引访问字典值的不同部分:

for (k,v) in sampleDict.iteritems():
    key          = k
    phone_number = v[0]
    last_name    = v[1][0]
    first_name   = v[1][0]
    # Do something

Each value is just a 2-element list, the first element corresponding to the phone number, and the second element, itself a list, with elements corresponding to the last and first name. 每个值只是一个2元素列表,第一个元素对应于电话号码,第二个元素本身就是一个列表,具有对应于姓氏和名字的元素。

But you could write the functions you're looking for with something like: 但是,您可以使用以下类似的代码编写所需的功能:

def is_john_here(d):
    for v in d.values():
        if v[1][1] == "john": return True
    return False

print is_john_here(sampleDict)  # False

Or 要么

def find_people_by_number(d, prefix):
    for v in d.values():
        if v[0].startswith(prefix):
            print ', '.join(v[1])

find_people_by_number(sampleDict, '654')  # Jones, Jennifer

Or (from comments) 或(根据评论)

def last_names(d):
    for v in d.values():
        print v[1][0]

last_names(sampleDict)    # Brown
                          # Jones

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

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