【问题标题】:Inserting separate dictionary into list of dictionaries将单独的字典插入字典列表
【发布时间】:2021-06-27 20:00:42
【问题描述】:

我正在使用一个 api,它返回格式为类似于此的字典列表(列表)的 json:

list_of_dictionaries = [
    [{'key1':0},{'key2':1}],
    [{'key1':2},{'key2':3}],
    [{'key1':4},{'key2':5}],
    [{'key1':6},{'key2':7}],
    [{'key1':8},{'key2':9}]
]

我还有一个单独的包含坐标的元组列表:

coordinates_tuple = namedtuple('Coordinates', ['x','y'])
coordinates_list = []
coordinates_list.append(coordinates_tuple((0),(0)))
coordinates_list.append(coordinates_tuple((1),(0)))
coordinates_list.append(coordinates_tuple((1),(1)))
coordinates_list.append(coordinates_tuple((0),(1)))
coordinates_list.append(coordinates_tuple((-1),(-1)))

我的目标是将每个坐标元组作为键/值对添加到 list_of_dictionaries 中,因此我创建了这个 for 循环,似乎可以实现所需的输出:

for i in range(len(list_of_dictionaries)):
    x = coordinates_list[i].x
    y = coordinates_list[i].y
    coordinates_dictionary = {'x' : x , 'y' : y}

    list_of_dictionaries[i].append(coordinates_dictionary.copy())
    print(list_of_dictionaries[i]) 

#output
#[{'key1': 0}, {'key2': 1}, {'x': 0, 'y': 0}]
#[{'key1': 2}, {'key2': 3}, {'x': 1, 'y': 0}]
#[{'key1': 4}, {'key2': 5}, {'x': 1, 'y': 1}]
#[{'key1': 6}, {'key2': 7}, {'x': 0, 'y': 1}]
#[{'key1': 8}, {'key2': 9}, {'x': -1, 'y': -1}]

假设这两个列表总是相同的长度并按顺序排列(coordinates_list[0] 将与 list_of_dictionaries[0] 匹配)- 这种方法是否有意义或有更好的解决方案?

【问题讨论】:

  • 注意,你显示的是字典列表...
  • 您正在遍历字典列表的 len,但您正在使用索引在坐标列表中查找值。您是否预见到它可能会超出索引范围?
  • @JoeFerndz 他说“假设这两个列表的长度总是相同的”
  • 此外,您正在遍历字典列表,但也附加到相同的字典列表。我不建议这样做。循环可能会变得混乱
  • @JoeFerndz 该列表是二维的。他正在添加到内部列表,而不是他正在迭代的列表。

标签: python list dictionary


【解决方案1】:

使用zip() 将两个列表一起处理。

for coord, d_list in zip(coordinates_list, list_of_dictionaries):
    d_list.append({'x': coord.x, 'y': coord.y})

【讨论】:

    【解决方案2】:
    from collections import namedtuple
    
    list_of_dicts = [
        [{'key1':0},{'key2':1}],
        [{'key1':2},{'key2':3}],
        [{'key1':4},{'key2':5}],
        [{'key1':6},{'key2':7}],
        [{'key1':8},{'key2':9}]]
    
    Coordinates = namedtuple('Coordinates', ['x','y'])
    coordinates_list = [Coordinates(0, 0), Coordinates(1, 0),
                        Coordinates(1, 1), Coordinates(0, 1),
                        Coordinates(-1, -1)]
    
    for my_list, coord in zip(list_of_dicts, coordinates_list):
        my_list.append(dict(coord._asdict())) # _asdict() will return OrderedDict
    
    print(list_of_dicts)
    

    还请注意,您在构造命名元组时过度使用括号。

    【讨论】:

      猜你喜欢
      • 2022-10-18
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 2021-09-09
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多