我有一个列表,里面有多个词典。我尝试使用OrderedDict()
以给定的顺序完成字典/列表组合的迭代。但是,我知道如何使用OrderedDict
,但我不知道如何使用OrderedDict()
创建列表中的有序字典。以下格式为storeItems
。我的想法是能够使用for item in storeItems: for key in item: return key, item[key]
迭代整个列表。这就是我所拥有的。
storeItems = OrderedDict()
#not sure how to declare the following list into OrderedDict() format
#the original dict/format to follow
#storeItems = [{
# "Name": "Auto-Enter",
# "Price": 30,
# "Max": 100
# }, {
# "Name": "Multiplier",
# "Price": 100,
# "Max": 5
# }, {
# "Name": "Factory",
# "Price": 200,
# "Max": 3
# }]
有什么想法吗?
预期输出应为以下(如果我是print()
而不是return
):
Name: Auto-Enter
Price: 30
Max: 100
Name: Multiplier
Price: 100
Max: 5
Name: Factory
Price: 200
Max: 3
因此,对于(排除的函数),我可以查看给定用户input().upper()
是否与整个列表中的项匹配,如果匹配,return True
。
答案 0 :(得分:2)
由于您无法创建包含重复键的词典,因此OrderedDict
不是您想要的,请注意您无法获得类似于词典的订单,因为如果您想要提取根据订单,您的商品应首先将商品存储在OrderedDict
中。
如果您想通过打印获取项目,只需使用str.join()
方法将字典转换为统一字符串:
>>> print('\n'.join(['\n'.join(['{}:{}'.format(i,j) for i,j in d.items()]) for d in storeItems]))
演示:
>>> print('\n'.join(['\n'.join(['{}:{}'.format(i,j) for i,j in d.items()]) for d in storeItems]))
Price:30
Max:100
Name:Auto-Enter
Price:100
Max:5
Name:Multiplier
Price:200
Max:3
Name:Factory