【问题标题】:Create new dictionaries based on names of keys of another dictionary根据另一个字典的键名创建新字典
【发布时间】:2022-11-15 01:52:26
【问题描述】:

我有一本字典“A”,

A = {'Industry1':1, 'Industry2':1, 'Industry3':1, 'Customer1':1, 'Customer2':1, 'LocalShop1':1, 'LolcalShop2':1 }
A = {'Industry1': 1,
 'Industry2': 1,
 'Industry3': 1,
 'Customer1': 1,
 'Customer2': 1,
 'LocalShop1': 1,
 'LolcalShop2': 1}

我想按键名分组并为每个“类别”创建新字典,名称应该自动生成

预期产出

Industry = {'Industry1': 1,
 'Industry2': 1,
 'Industry3': 1,
}
Customer = { 'Customer1': 1,
 'Customer2': 1,
}
LocalShop = { 'LocalShop1': 1,
 'LolcalShop2': 1}

你们能给我一个实现这个输出的提示吗?

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您可以使用set() 来识别输入字典中的唯一键,删除最后一个字符。

    然后,对于每个键,您可以从 input_dict 检索所有条目,并使用先前检索到的唯一键和最初作为值存在的键创建一个新字典。

    然后简单地将新密钥的字符串与旧密钥(减去最后一个字符)进行比较。

    完整代码:

    A = {
        'Industry1': 1,
        'Industry2': 1,
        'Industry3': 1,
        'Customer1': 1,
        'Customer2': 1,
        'LocalShop1': 1,
        'LocalShop2': 1
    }
    
    unique_keys = set([x[:-1] for x in A.keys()])  # {'Customer', 'LocalShop', 'Industry'}
    
    new_dict = {}
    for k in unique_keys:
        new_dict[k] = {key:val for key,val in A.items() if key[:-1]==k}
    
    # new_dict = {'LocalShop': {'LocalShop1': 1, 'LocalShop2': 1}, 'Industry': {'Industry1': 1, 'Industry2': 1, 'Industry3': 1}, 'Customer': {'Customer1': 1, 'Customer2': 1}}
    
    Industry = new_dict['Industry']
    Customer = new_dict['Customer']
    LocalShop = new_dict['LocalShop']
    

    【讨论】:

      【解决方案2】:

      为了这个答案的目的,我假设字典 A 中的每个键都包含单词“Industry”、“Customer”或“Shop”。这使我们能够通过检查每个键是否包含某个子字符串(即“Industry”)来检测每个条目需要属于哪个类别。如果此假设不适用于您的特定情况,则您必须找到一种不同的方式来编写下面解决方案中更适合您的情况的 if/elif 语句。

      这是一种方法。您为每个类别制作一个新词典,并检查每个键中是否包含“Industry”、“Customer”或“Shop”。

      industries = {}
      customers = {}
      shops = {}
      
      for key, value in A.items():
          if "Industry" in key:
              industries[key] = value
          elif "Customer" in key:
              customers[key] = value
          elif "Shop" in key:
              shops[key] = value
      

      另一个更简洁的版本是你有一个嵌套字典来存储你所有的类别,每个类别在主类别中都有自己的字典。如果您需要添加更多类别,这将在将来有所帮助。您只需将它们添加到一个地方(在字典定义中),代码就会自动调整。

      categories = {
          "Industry": {},
          "Customer": {},
          "Shop": {},
      }
      
      for key, value in A.items():
          for category_name, category_dict in categories.items():
              if category_name in key:
                  category_dict[key] = value
      

      如果您无法从条目的字符串中检测到类别,那么您可能必须将该类别信息存储在 A 中的键或每个条目的值中,以便在尝试过滤所有内容时可以检测类别.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-23
        • 1970-01-01
        • 1970-01-01
        • 2022-10-05
        • 2023-01-11
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        相关资源
        最近更新 更多