在For循环,输出排序中将键/值对添加到Python字典

时间:2018-03-19 00:16:59

标签: python nosql amazon-dynamodb

我正在尝试将用户名字段添加到输出列表中的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

1 个答案:

答案 0 :(得分:0)

订单不是由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)