简体   繁体   中英

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. 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)

Here is a solution using 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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