在不知道特定键的情况下迭代Python Dictionary

时间:2015-03-16 09:32:54

标签: python

我似乎无法弄清楚如何编写这段Python代码。

我需要从文件中读取内容,即:

Jake FJ49FJH
Bob FJ49GKH

我已将文件导入字典。然后我检查号牌(名字后面)是否包含两个字母,两个数字,然后三个字母的序列。这是代码的一部分:

d = {} # Blank Dictionary

with open("plates.txt") as f:
  d = dict(x.rstrip().split(None, 1) for x in f) # Put file into dictionary

names = d.keys()
print(names)
#carReg = ??


a,b,c = carReg[:2],carReg[2:4],carReg[4:]
if all((a.isalpha(),b.isdigit(),c.isalpha(),len(c)== 3)):
    print("Valid Reg")
else:
    print("Invalid Reg")
    # Now get the name of the person with the invalid carReg

正如您所看到的,我不知道要为carReg添加什么。我需要循环遍历字典,就像在列表中一样,你可以使用整数来获取列表的一部分。如果程序返回Invalid Reg,那么我需要获取无效reg所属的密钥 - 这将是一个名称。

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:4)

迭代dict.items();它会从字典中提供(key, value)对:

for name, car_registration in d.items():
相关问题