在嵌套字典中查找特定键的值
Posted
技术标签:
【中文标题】在嵌套字典中查找特定键的值【英文标题】:Find the value of a specific key in a nested dictionary 【发布时间】:2020-02-16 14:19:55 【问题描述】:我有一个嵌套字典
customer_order = order0
'Orientation': what_orientation, 'Size': what_size, 'sizecost': size_cost,
'eyelets': how_many_eyelets, 'eyeletcost': eyelet_cost, 'material': what_material,
'materialcost': material_cost, 'ropes': need_ropes, 'ropecost': rope_cost,
'image': need_image, 'imagecost': 0, 'wording': what_wording, 'wordcost':word_cost
order1'Orientation': what_orientation, 'Size': what_size, 'sizecost': size_cost,
'eyelets': how_many_eyelets, 'eyeletcost': eyelet_cost, 'material': what_material,
'materialcost': material_cost, 'ropes': need_ropes, 'ropecost': rope_cost,
'image': need_image, 'imagecost': 0, 'wording': what_wording, 'wordcost':word_cost
我需要做的是获取以下键的值
sizecost
eyeletcost
materialcost
ropecost
wordcost
如何循环获取这些值并将它们添加到运行总计中?
谢谢
我尝试了下面的代码,但得到了错误
for key, value in cust_details:
ValueError:解包的值太多(预计 2 个)
对于 cust_order,customer_order.items() 中的 cust_details: print("\n订单:", cust_order) 对于 cust_details 中的键、值: if (key == "sizecost"): 总成本 += 价值
if (key == "eyeletcost"):
totalcosts += value
if (key == "materialcost"):
totalcosts += value
if (key == "ropecost"):
totalcosts += value
if (key == "wordcost"):
totalcosts += value
总成本 += 价值
【问题讨论】:
首先你的字典不是一个有效的python对象。你能把它变成一个有效的python对象吗? 【参考方案1】:您可以使用recurssion
def look(key,d,val = None):
if val is None:
val = []
if key in d.keys():
val.append(d.get(key))
else:
for i,j in d.items():
if isinstance(j,dict):
look(key,j,val)
return val
现在尝试拨打:look("sizecost", customer_order )
【讨论】:
感谢您正确布局。我已经正确地将它放入模板中,但是当我发布它时,它却非常可怕。以上是关于在嵌套字典中查找特定键的值的主要内容,如果未能解决你的问题,请参考以下文章