[英]Adding key to dict to get a dict of dicts
我有一个看起来像的字典
{'apples' : 'in_stock', 'bananas' : 'in_stock', 'oranges' : 'not_in_stock'}
我想遍历这些并添加价格(或任何其他字段)。 最终目标是计数。 我在想象最终结果会非常像这样。
{
{'apples' : 'in_stock', 'count' : 700},
{'bananas' : 'in_stock', 'count' : 3},
{'oranges' : 'not_in_stock', 'count' : 0}
}
我在将密钥添加到每个初始初始密钥时遇到问题。
这是我正在使用的代码,以尝试实现这一目标。
store_dict = {}
my_query = my_sql_query
for item in my_query:
if item['count'] in store_dict:
store_dict[item['count']] += 1
else:
store_dict[item['count']] = 1
这里有两个使用列表推导式和字典推导式的选项。 由于您要求的格式不是有效的 Python 数据结构,因此我将介绍如何创建列表以及如何创建 dict。
In [17]: from random import randint
In [18]: from pprint import pprint
In [19]: d = {'apples' : 'in_stock', 'bananas' : 'in_stock', 'oranges' : 'not_in_stock'}
In [20]: l1 = [ { product : stock, 'count' : randint(1,100) if stock == 'in_stock' else 0 } for product, stock in d.items() ]
In [21]: pprint(l1)
[{'apples': 'in_stock', 'count': 56},
{'count': 0, 'oranges': 'not_in_stock'},
{'bananas': 'in_stock', 'count': 74}]
In [22]: d1 = { product : { 'stock' : stock, 'count' : randint(1,100) if stock == 'in_stock' else 0 } for product, stock in d.items() }
In [23]: pprint(d1)
{'apples': {'count': 32, 'stock': 'in_stock'},
'bananas': {'count': 83, 'stock': 'in_stock'},
'oranges': {'count': 0, 'stock': 'not_in_stock'}}
In [24]:
我认为这
{
'apples': {'in_stock':True, 'count' : 700},
'bananas': {'in_stock':True, 'count' : 3},
'oranges': {'in_stock':False, 'count' : 0}
}
是您正在寻找的结构。 要将原始字典转换为上面的字典,您需要有另一本字典来匹配项目:
original = {'apples' : 'in_stock', 'bananas' : 'in_stock', 'oranges' : 'not_in_stock'}
to_add = {'apples' : 700, 'bananas' : 3, 'oranges' : 0}
ret_dict = {}
for key, item in original.items():
ret_dict[key] = {
'in_stock': True if original[key] == 'in_stock' else False,
'size':to_add[key]
}
print ret_dict
您可以遍历您的代码并以正确的格式构建一个新字典
d = {'apples' : 'in_stock', 'bananas' : 'in_stock', 'oranges' : 'not_in_stock'}
d2 = []
for key in d.keys():
d2.append({key = d[key], "count" : 700})
您也可以选择以不同的方法使用原始字典并构建一些效果
dictionary = {
"apples" : {"instock" : True, "count": 700},
"oranges" : {"instock": True, "count": 12}
}
可以通过以下方式访问这个新词典
dictionary["apples"]["count"] = 500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.