使用组合键创建一个新的dict&来自1个字典的值和来自另一个字典的值

时间:2016-05-11 13:33:04

标签: python dictionary

我得到了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}

我希望通过bookID在2个dicts之间进行匹配,并根据标题和性别来计算平均评分,

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的元组,列表和词汇知之甚少。我应该如何解决这个问题才能得到预期的结果呢?非常感谢示例代码。

谢谢,Lobbie

2 个答案:

答案 0 :(得分:3)

您可以使用dict.keys()功能获取dict2的密钥,例如:

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

然后,您可以拆分组合键,例如:

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

答案 1 :(得分: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}

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