Python 循环打印列表中的字典键 (OrderedDict)
Python Print key of dictionarys (OrderedDict) within list withloop
我正在尝试找出如何打印包含 3 个 OrderedDict()
的列表 storeItems
,并能够打印 key
和 value
每个 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
的原始格式
storeItems
中的每个元素都是一个字典(OrderedDict
只是一个跟踪插入顺序的子类),所以只需循环dict.items()
method:
for odict in storeItems:
for key, value in odict.items():
print(key, value)
我正在尝试找出如何打印包含 3 个 OrderedDict()
的列表 storeItems
,并能够打印 key
和 value
每个 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
storeItems
中的每个元素都是一个字典(OrderedDict
只是一个跟踪插入顺序的子类),所以只需循环dict.items()
method:
for odict in storeItems:
for key, value in odict.items():
print(key, value)