Python打印列表withloop中的dictionarys(OrderedDict)键

时间:2015-10-07 15:31:57

标签: python python-3.x ordereddictionary

我正在尝试弄清楚如何打印包含3 storeItems的列表OrderedDict(),并且能够为每个列表打印keyvalue OrderedDict。我不知道如何解决这个问题,这就是我试过的,它给了我一个TypeError: string indices must be integers

storeItems = [{}, {}, {}]
storeItems[0] = OrderedDict()
storeItems[1] = OrderedDict()
storeItems[2] = OrderedDict()

storeItems[0]['Name'] = 'Auto-Enter'
storeItems[0]['Price'] = 30
storeItems[0]['Max'] = 100

storeItems[1]['Name'] = 'Multiplier'
storeItems[1]['Price'] = 100
storeItems[1]['Max'] = 5

storeItems[2]['Name'] = 'Factory'
storeItems[2]['Price'] = 100
storeItems[2]['Max'] = 3

#the original layout of the storeItems

#storeItems = [{
#        "Name": "Auto-Enter",
#        "Price": 30,
#        "Max": 100
#    }, {
#        "Name": "Multiplier",
#        "Price": 100,
#        "Max": 5
#    }, {
#        "Name": "Factory",
#        "Price": 200,
#        "Max": 3
#    }]
i = 0
for value in storeItems:
    for key in value:
        for i in range(0, 2):
            print(storeItems[i][key], storeItems[i][key][value])

注意事项

我发现,for value in storeItems: print(value)会为每一行打印OrderedDict([('Name': 'Auto-Enter', ...)])print(storeItems[0]['Name'])输出Auto-Enter。我似乎很难把它变成循环。

我更喜欢这样做尽可能接近storeItems

的原始格式

1 个答案:

答案 0 :(得分:2)

storeItems中的每个元素都是一个字典(OrderedDict只是跟踪插入顺序的子类),所以只需循环遍历dict.items() method

for odict in storeItems:
    for key, value in odict.items():
        print(key, value)