2017-10-13 148 views
-1

我有非常简单的2阶段字典的问题。 我的字典中有键(数字),第二键(数字)和姓名公司的值。 我需要检查只有密钥没有1,因为我知道只有可能性,“福特”名称出现 - 字典[我] [1] 而且正如你所看到的 - 字符串与密钥不等于100%。钥匙可以包含“福特”(但钥匙的另一部分名称:“福特汽车”),所以如果“福特”出现在每个词典[i] [1]中 - 将该键分配给空字典“MATCHINGITEMS”比较嵌套字典中的值

matchingitems[1] = "Ford" 
matchingitems[2] = "Ford" etc 

你能帮帮我吗?

Dictionary = { „1” : { „1” : "Ford Motor", 
        „2” : "Volkswagen Autos" 
         } 
       "2" : { "1" : "Ducati", 
         "2" : "Yamaha" 
         } 
       "3" : { "1" : "Ford", 
         "2" : "SEAT" 
        } 
       } 
matchingitems = {} 
i = 0 
for value in Dictionary.items(): 
    for key in Dictionary.items[value]: 
     i += 1 
     if "Ford" in Dictionary[i][1]: 
      matchingitems[i] = "Ford" 

回答

2

如果我理解你正确地这样做,你需要什么:

Dictionary = { "1" : { "1" : "Ford Motor", 
        "2" : "Volkswagen Autos" 
         }, 
       "2" : { "1" : "Ducati", 
         "2" : "Yamaha" 
         }, 
       "3" : { "1" : "Ford", 
         "2" : "SEAT" 
        } 
       } 
matchingitems = {} 

for key,value in Dictionary.items(): 
    if 'Ford' in value['1']: 
     matchingitems[key] = value['1'] 

print(matchingitems) 
+0

不会'i'是随机的字典是(大概)不是一个有序字典,因此从枚举指数可能会改变? –

+0

是的,你是对的。我已经相应地更改了代码。这也不是OP想要的。 – elzell

+0

此外,键可能增加超过1,我认为你需要'matchingitems.append(值['1'])' –