[英]Iterate through Python Dictionary without knowing the specific keys
I can't seem to figure out how to write this piece of Python Code. 我似乎无法弄清楚如何编写这段Python代码。
I need to read something in from a file, which is this: 我需要从文件中读取一些内容,这是:
Jake FJ49FJH
Bob FJ49GKH
I've imported the file into a dictionary. 我已将文件导入字典。 I then check if the number plate (following the names) contains the sequence of two letters, two numbers, then three letters.
然后,我检查一下车号牌(跟随名称)是否包含两个字母,两个数字,然后三个字母的序列。 Here is that part of the code:
这是代码的一部分:
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
As you can see, I don't know what to put for carReg
. 如您所见,我不知道要为
carReg
放置什么。 I need to loop through the dictionary, like in a list when you can use an integer to get part of the list. 我需要遍历字典,就像在列表中一样,当您可以使用整数来获取列表的一部分时。 If the program returns
Invalid Reg
, then I need to get the key that the invalid reg belongs to - which will be a name. 如果程序返回
Invalid Reg
,那么我需要获取无效reg所属的密钥-这将是一个名称。
Any help appreciated. 任何帮助表示赞赏。
Iterate over dict.items()
; 遍历
dict.items()
; it'll give you the (key, value)
pairs from the dictionary: 它会给你字典中的
(key, value)
对:
for name, car_registration in d.items():
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.