我的字典看起来像这样:
entryDir = {'cities': [['US', 'AU']], 'countries': [['DK', 'US']]}
如果每个列表中不同键的值匹配,我试图弄清楚如何打印确认。 在伪代码中:
for each key:
# {cities} {countries}
if a value for that key matches the value of another key:
#cities:US == countries:US
print key1:value1,key2:value2,"match found"
#cities:US,countries:US,"match found
if they don't match:
#cities:AU == countries:DK
print key1:value2,key2:value1,"no match"
cities:AU,countries:DK,"no match found"
到目前为止我所拥有的是:
for key1 in entryDir:
for key2 in entryDir:
if key1 != key2:
if entryDir[key1][0] == entryDir[key2][0]:
print entryDir[key1][0],entryDir[key2][0],"match found"
if entryDir[key1][0] != entryDir[key2][0]:
print entryDir[key2][0],entryDir[key2][0],"no match found"
但这并不是正确匹配或不匹配。
答案 0 :(得分:-1)
您还将键值与其自身值进行比较。请尝试改为:
for key1 in entryDir:
for key2 in entryDir:
if key1 != key2:
if entryDir[key1][0] == entryDir[key2][0]:
print entryDir[key1][0],entryDir[key2][0],"match found"
else:
print entryDir[key2][0],entryDir[key2][0],"no match found"
修改强>
如果您希望每个键有多个值,则需要这样做:
for key1 in entryDir:
for key2 in entryDir:
if key1 != key2:
for val in entryDir[key1]:
if val in entryDir[key2]
print val, "match found"
请注意根据输入的大小计算需要计算的(可能)可怕时间。
答案 1 :(得分:-1)
我已经解决了。 我可以使用entryDir.keys()生成的数组的索引作为比较entryDir中的值的索引。
所以,而不是:
for key1 in entryDir:
for key2 in entryDir:
if key1 != key2:
for val in entryDir[key1]:
if val in entryDir[key2]
print val, "match found"
我们可以做到:
keyList=entryDir.keys()
if keyList[0] != keyList[1]:
if entryDir[keyList[0]][0] == entryDir[keyList[1]][0]:
print entryDir[keyList[0]][0], "match found"
else:
print entryDir[keyList[0]][0],entryDir[keyList[1]][0], "no match"