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

1586010002-jmsa.png

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

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

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值