sampleDict={ “A1”:[“234-234-2234”, [“Brown”, “Bill”] ], “B2”:[“654-564-5564”,[“Jones”,”Jennifer”]] }
我必须检查字典中是否有"john"
,并打印电话号码以"654"
开头的所有人的姓名和/或
我的代码是:
for i in sampleDict.keys():
for key in sampleDict[i]:
print(key)
如何在列表中打印姓氏:" Brown"
答案 0 :(得分:0)
您好像不关心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
答案 1 :(得分:0)
通常,您可以通过列表索引访问字典值的不同部分:
for (k,v) in sampleDict.iteritems():
key = k
phone_number = v[0]
last_name = v[1][0]
first_name = v[1][0]
# Do something
每个值只是一个2元素列表,第一个元素对应于电话号码,第二个元素本身就是一个列表,其元素对应于姓氏和名字。
但你可以用以下内容编写你正在寻找的功能:
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
或者
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
或(来自评论)
def last_names(d):
for v in d.values():
print v[1][0]
last_names(sampleDict) # Brown
# Jones