【问题标题】:compare values in nested dictionary比较嵌套字典中的值
【发布时间】:2017-10-13 08:10:38
【问题描述】:

我对非常​​简单的两阶段字典有疑问。 我的字典在值中有键(数字)、第二键(数字)和名称公司。 我只需要检查 1 号键,因为我知道“福特”名称出现的唯一可能性是字典 [i][1] 正如您所看到的 - 字符串与键 100% 不相等。键可以包含“Ford”(但键中有另一个部件名称:“Ford Motor”),因此如果每个 Dictionary[i][1] 中出现“Ford” - 将此键分配给空字典“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"

【问题讨论】:

    标签: python dictionary nested


    【解决方案1】:

    如果我理解正确,这就是你所需要的:

     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)
    

    【讨论】:

    • i 不会是随机的,因为 dict(可能)不是有序的 dict,因此 enumerate 的索引可能会改变?
    • 是的,你是对的。我已经相应地更改了代码。这也不是 OP 想要的。
    • 另外,key 的增量可能会超过 1,我认为你需要 matchingitems.append(value['1'])
    • 请重新加载我的答案,我同时更改了它:)
    • :-) 我给你 +1 的持久性!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多