【问题标题】:Inserting items into the middle of a dict将项目插入到字典的中间
【发布时间】:2018-07-23 05:46:03
【问题描述】:

我有一个字典列表,其中所有字典都包含相似的项目,但有些字典缺少某些项目。以下是它的外观示例:

data = [
         { 
           'city' : Toronto,
           'colour' : blue
         },
         {
           'city' : London,
           'country' : UK
           'colour' : green,
           'name' : Alex
         },
         {
           'city' : Kingston,
           'colour' : purple,
           'name' : Alex
         }
      ]

我需要通过将项目(具有相同的键但空白值)插入到较小的字典中来匹配最大字典的格式。我还需要保留键的顺序,所以我不能只在最后插入它们。按照前面的例子,它看起来像这样:

data = [
         { 
           'city' : Toronto,
           'country' : ,
           'colour' : blue,
           'name' : 
         },
         {
           'city' : London,
           'country' : UK
           'colour' : green,
           'name' : Alex
         },
         {
           'city' : Kingston,
           'country' : ,
           'colour' : purple,
           'name' : Alex
         }
       ]

我不知道如何循环并添加条目到每个字典,因为我比较的字典大小不同。我尝试复制最大的字典并对其进行编辑,在每个字典的末尾添加空白值并重新格式化它们,并在循环时创建新的字典,但到目前为止没有任何效果。 到目前为止,这是我的代码(其中 all_keys 是按正确顺序排列的所有键的列表)。

def format_data(input_data, all_keys)

    formatted_list = [{} for i in range(len(input_data)) ]
    increment = 0

    for i in range(len(input_data)):
        for key, value in input_data[i].items():

            if (key == all_keys[increment]):
                formatted_list[i][increment].update(all_keys[increment], ''))

            else:
                formatted_list[i][inrement].update(key, value)

            increment += 1
        increment = 0
    return formatted_list

如何格式化?谢谢!

【问题讨论】:

  • 在 Python 3.7 之前的字典是无序的。

标签: python list dictionary


【解决方案1】:

字典被认为是无序的(除非您使用的是 Python 3.7+)。如果您需要特定的顺序,则必须明确指定。

对于 Python collections.OrderedDict:没有“插入字典中间”的概念。

下面的例子使用set.union来计算所有键的并集;和sorted 按字母顺序对键进行排序。

from collections import OrderedDict

keys = sorted(set().union(*data))
res = [OrderedDict([(k, d.get(k, '')) for k in keys]) for d in data]

结果:

print(res)

[OrderedDict([('city', 'Toronto'),
              ('colour', 'blue'),
              ('country', ''),
              ('name', '')]),
 OrderedDict([('city', 'London'),
              ('colour', 'green'),
              ('country', 'UK'),
              ('name', 'Alex')]),
 OrderedDict([('city', 'Kingston'),
              ('colour', 'purple'),
              ('country', ''),
              ('name', 'Alex')])]

【讨论】:

    【解决方案2】:

    你可以使用set:

    import json
    d = [{'city': 'Toronto', 'colour': 'blue'}, {'city': 'London', 'country': 'UK', 'colour': 'green', 'name': 'Alex'}, {'city': 'Kingston', 'colour': 'purple', 'name': 'Alex'}]
    full_keys = {i for b in map(dict.keys, d) for i in b}
    final_dict = [{i:b.get(i) for i in full_keys} for b in d]
    print(json.dumps(final_dict, indent=4))
    

    输出:

    [
     {
        "colour": "blue",
        "city": "Toronto",
        "name": null,
        "country": null
     },
     {
        "colour": "green",
        "city": "London",
        "name": "Alex",
        "country": "UK"
    },
    {
        "colour": "purple",
        "city": "Kingston",
        "name": "Alex",
        "country": null
     } 
    ]
    

    【讨论】:

    • 这会将新条目添加到每个字典的末尾。我的其余代码依赖于所有键的顺序相同。还有其他方法吗?
    • @Aya 在 Python 3.7 之前,字典是无序的。无论哪种方式,它都不应该有太大区别,因为将根据您想要的输出添加新条目。
    猜你喜欢
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多