簡體   English   中英

如何檢查字典中的列表元素是否與字典中的鍵相同,然后用列表元素打印鍵的值

[英]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'}

例如,我有這 3 部詞典。 我需要檢查 recipedict 的第二個值的內部元素是否在供應字典中。 所以檢查面包和黃油是否在供應指令中。 如果 bread and butter 在 supplydict 中,則獲取 supplydict 的第二個值,在本例中為 james and allen,並獲取 supplier dict 中的第一個值。 然后打印相互關聯的值

ingredient: bread

amount needed: 13

supplier: james

supplier contact: 12345234



ingredient: butter

amount needed: 4

supplier: allen

supplie contact: 17682342

我嘗試將所有列表放在一起,但我只打印具有相關字典值的整個列表

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)

試試這個:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM