简体   繁体   English

将python中的元组列表转换为字典

[英]Converting list of tuples in python to dictionary

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’),

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. 编写Python函数likes_relation(network),该函数将元组列表作为参数(采用上述格式),然后返回字典作为结果。 The outputdictionary has strings for keys (representing names of people) and lists of strings for values (representing lists of names of people). outputdictionary具有用于键的字符串(代表人物名称)和用于值的字符串列表(代表人物名称列表)。

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

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): 我得到了:def likes_relations(network):
likes = {} for k, v in network: 对于网络中的k,v,喜欢= {}:

after than i am a bit lost as its not like any of the examples we did in class 之后,我有点迷茫,因为它不像我们在课堂上做过的任何例子

Use either defaultdict(list) or dict.setdefault(..., []) - there's not much difference in performance or readability, so it's really a matter of taste. 使用defaultdict(list)dict.setdefault(..., []) -性能或可读性没有太大差异,因此这实际上是一个问题。 I prefer using setdefault : 我更喜欢使用setdefault

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

Here is a solution using defaultdict : 这是使用defaultdict的解决方案:

def likes_relation(friendface):
    d = defaultdict(list)
    for k, v in friendface:
        d[k].append(v)
    return d

Result: 结果:

>>> for k,v in likes_relation(f).items():
    print (k, v)


Hera ['Aphrodite']
Apollo ['Aphrodite']
Aphrodite ['Apollo', 'Zeus', 'Athena']
Zeus ['Apollo', 'Aphrodite', 'Athena', 'Hera']
Athena ['Hera', 'Aphrodite']

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM