【问题标题】:Appending Key/Value Pairs to Python Dictionary in For Loop, Output Ordering在 For 循环中将键/值对附加到 Python 字典,输出排序
【发布时间】:2018-03-19 00:16:59
【问题描述】:

我正在尝试将用户名字段添加到输出列表中的 3 个字典中的每一个中,然后我想将每个字段作为键/值对作为字段#/字段值添加到其各自的字典中,以便轻松放置项目在 DynamoDB 中。但是,当我在输出列表中输出字典的结果时,我收到了乱序字段(请记住,每个对象都有数千个字段)。

   #Result stores a list of dicts with username key/value pair and a long list of fields
    result = [{ username: nasa , fields: [Nebula, Moon, Star, ...]},{ username: nationalgeographic, fields: [Grass, Tree, ...] },{ username: kingjames, fields[Basketball, Hardwood, Jersey, ...]}]

    for i in result:
        #For each dict in list
        num = 1
        item = {}
        item['username'] = i['username']
        for tag in i['fields']:
            label_string = 'label' + str(num)
            item[label_string] = tag
            num += 1
        output.append(item.copy())
        #Output should store 3 dicts with username, and labels with tags
    for user in output:
        for key, value in user.items():
            print(key, value)

预期输出:

username nasa
field1 Nebula
field2 Moon
field3 Star
.
.
.
username nationalgeographic
field1 Grass
field2 Tree
.
.
.
username kingjames
field1 Basketball
field2 Hardwood
field3 Jersey
.
.
.

实际输出

username nasa
field333 Black Hole
field282 Asteroid
field122 Mars
.
.
.
username nationalgeographic
field122 Moss
field3323 Bark
field212 Wood
.
.
.
username kingjames
field233 Shoe
field9331 Headband
field211 Mesh

【问题讨论】:

    标签: python nosql amazon-dynamodb


    【解决方案1】:

    订单不是由 Python 中的 dict 维护的。如果您想按插入顺序保留密钥,可以使用OrderedDict

    from collections import OrderedDict
    

    你的代码会变成

    #Result stores a list of dicts with username key/value pair and a long list of fields
    result = [{ username: nasa , fields: [Nebula, Moon, Star, ...]},{ username: nationalgeographic, fields: [Grass, Tree, ...] },{ username: kingjames, fields[Basketball, Hardwood, Jersey, ...]}]
    
    for i in result:
        #For each dict in list
        num = 1
        item = OrderedDict()
        item['username'] = i['username']
        for tag in i['fields']:
            label_string = 'label' + str(num)
            item[label_string] = tag
            num += 1
        output.append(item.copy())
        #Output should store 3 dicts with username, and labels with tags
    for user in output:
        for key, value in user.items():
            print(key, value)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-12
      • 2021-05-19
      • 1970-01-01
      • 2022-12-13
      • 2019-06-14
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多