簡體   English   中英

使用組合鍵和1個字典的值以及另一個字典的值創建一個新字典

[英]Create a new dict with combo key & value from 1 dict and value from another dict

我得到了2則字典

# dict format - bookID:title
dict1 = {'book1':'Lord of the Rings','book2':'Animal Farm','book3':'Lilliput'}

# dict format - bookID_gender:rating
dict2 = {'book1_F':5, 'book2_M':4, 'book1_M':3, 'book1_M':2}

我想按2個字典之間的bookID進行匹配,並按標題和性別計算平均評分以輸出,

book1 - Lord of the Rings - F - 5.0
book1 - Lord of the Rings - M - 2.5
book2 - Animal Farm - M - 4
book3 - Lilliput - no rating

我最初想在dict2中拆分組合鍵,但得到的錯誤拆分無法在dict鍵上完成。

編輯

for bookid, title in dict1.items():
    if bookid == dict2.keys().spilt('_')[0]:
        print('test ok')
    else:
        print('test not ok')

錯誤消息是,

    if bookid == dict2.keys().spilt('_')[0]:
AttributeError: 'dict_keys' object has no attribute 'spilt'

我是Python的新手,對Python的元組,列表和字典的了解非常有限。 我應該如何處理以獲得預期的結果? 樣例代碼非常感謝。

謝謝,羅比

您可以使用dict.keys()函數來獲取dict2的鍵,例如:

>>> dict2.keys()
['book1_F', 'book1_M', 'book2_M']

然后,您可以拆分組合鍵,例如:

>>> for value in dict2.keys():
...     value.split('_')[0]
... 
'book1'
'book1'
'book2'

更正了代碼。

# dict format - bookID:title
dict1 = {'book1':'Lord of the Rings','book2':'Animal Farm','book3':'Lilliput'}

# dict format - bookID_gender:rating
dict2 = {'book1_F':5, 'book2_M':4, 'book1_M':3, 'book1_M':2}

for bookid, title in dict1.items():
    for bookid_1 in dict2.keys():
        if bookid == bookid_1.split('_')[0]:
            print('test ok')
        else:
            print('test not ok')

輸出量

test ok
test ok
test not ok
test not ok
test not ok
test ok
test not ok
test not ok
test not ok

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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