[英]How to check if list element in a dictionary is the same as the key in a dictionary and then print the value of the key with the list element
recipedict = {'sandwich':['a buttered sandwich',[['bread','13'],['butter','4']]]}
supplydict = {'bread':['150','15','james'],'butter':['15','12','allen'],'sugar':['15','12','marc']}
supplierdict = {"james":'12345234',"allen":'17682342'}
for example I have these 3 dictionaries.例如,我有这 3 部词典。 I need to check if the inner element of the second value of the recipedict is in the supply dict.我需要检查 recipedict 的第二个值的内部元素是否在供应字典中。 so check if bread and butter is in the supply dict.所以检查面包和黄油是否在供应指令中。 If bread and butter is in the supplydict, get the second value of the supplydict, in this case it would be james and allen, and get the first value in supplier dict.如果 bread and butter 在 supplydict 中,则获取 supplydict 的第二个值,在本例中为 james and allen,并获取 supplier dict 中的第一个值。 then print the associated values with each other然后打印相互关联的值
ingredient: bread
amount needed: 13
supplier: james
supplier contact: 12345234
ingredient: butter
amount needed: 4
supplier: allen
supplie contact: 17682342
i tried getting all the lists together but i only print the whole list with the associated dictionary value我尝试将所有列表放在一起,但我只打印具有相关字典值的整个列表
def flatten(l):
return [item for sublist in l for item in sublist]
for key, value in recipedict.items():
onevalue = value[1]
#print(onevalue)
actuallist = [item[0] for item in onevalue]
valew = []
for k in actuallist:
if k in supplydict:
valuee = supplydict.get(k)
valew.append(valuee[2])
print(valew)
z = flatten(onevalue)
#print(y)
n = 1
word = valew
for i in range(n, len(onevalue) + n, n + 1):
onevalue.insert(i, word)
print(onevalue)
Try this:试试这个:
goal = 'sandwich'
for ingredient, needed in recipedict[goal][1]:
_, _, supplier = supplydict[ingredient]
contact = supplierdict[supplier]
print('ingredient', ingredient)
print('amount needed', needed)
print('supplier', supplier)
print('supplier contact', contact)
print()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.