将python中的元组列表转换为字典 [英] Converting list of tuples in python to dictionary

查看:1378
本文介绍了将python中的元组列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下一个社交网络网站,该网站可以让人们指定自己喜欢的其他人.

Imagine a social network website which allows people to specify which other people they like.

我们可以将有关谁喜欢谁的信息存储在元组列表中,例如分配给的人

We can store information about who likes who in a list of tuples, such as the one assigned to

friendface below:
    friendface = [
    (’Zeus’,’Apollo’),
    (’Zeus’,’Aphrodite’),
    (’Apollo’,’Aphrodite’),
    (’Athena’,’Hera’),
    (’Hera’,’Aphrodite’),
    (’Aphrodite’,’Apollo’),
    (’Aphrodite’,’Zeus’),
    (’Athena’,’Aphrodite’),
    (’Aphrodite’,’Athena’),
    (’Zeus’,’Athena’),
    (’Zeus’,’Hera’),

编写一个Python函数likes_relation(network),该函数将一个元组列表作为 其参数(采用上述格式),并返回字典作为结果. outputdictionary具有用于键的字符串(代表人物名称)和用于值的字符串列表(代表人物名称列表).

Write a Python function likes_relation(network) which takes a list of tuples as its argument (in the format described above) and returns a dictionary as its result. The outputdictionary has strings for keys (representing names of people) and lists of strings for values (representing lists of names of people).

词典中的每个人都与他们所喜欢的所有人的列表相关联.例如,将该函数应用于好友列表时,其行为应如下所示:

Each person in the dictionary is associated with the list of all and only the people that they like. For example, the function should behave like so when applied to the friendface list:

 likes_relation(friendface)
    { 'Aphrodite': ['Apollo', 'Zeus', 'Athena'],
    'Hera': ['Aphrodite'],
    'Zeus': ['Apollo', 'Aphrodite', 'Athena', 'Hera'],
    'Apollo': ['Aphrodite'],
    'Athena': ['Hera', 'Aphrodite'] }

抱歉,应该从示例考试问题列表中添加,但没有给出答案. 我得到了: def likes_relations(网络):
喜欢= {} 对于网络中的k,v:

Sorry should add it's from a list of example exam questions but no answers are given. I got as far as: def likes_relations(network):
likes = {} for k, v in network:

那之后我有点迷失了,因为它不像我们在课堂上做过的任何例子

after than i am a bit lost as its not like any of the examples we did in class

推荐答案

使用defaultdict(list)dict.setdefault(..., [])-在性能或可读性上没有太大差异,因此这实际上是一个品味问题.我更喜欢使用setdefault:

Use either defaultdict(list) or dict.setdefault(..., []) - there's not much difference in performance or readability, so it's really a matter of taste. I prefer using setdefault:

likes = {}
for k, v in friendface:
    likes.setdefault(k, []).append(v)

这篇关于将python中的元组列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆