Roelland
Roelland

Reputation: 193

Changing the type of values of a dictionary from list to set

I have a dictionary in python that looks like this:

{'Alan Turing': ['Alanin', 'Anting'], 'Donald Knuth': ['Donut'], 'Claude Shannon': ['Cannon']}

Now I want to change the type of values of a dictionary from list to set.

What is an easy way to do this?

Upvotes: 1

Views: 1073

Answers (1)

Tagc
Tagc

Reputation: 9072

This code will cause all dictionary values to change from lists to sets:

d = {'Alan Turing': ['Alanin', 'Anting'], 'Donald Knuth': ['Donut'], 'Claude Shannon': ['Cannon']}

for k, v in d.items():
    d[k] = set(v)

print(d)

Output

{'Donald Knuth': {'Donut'}, 'Claude Shannon': {'Cannon'}, 'Alan Turing': {'Anting', 'Alanin'}}

Upvotes: 2

Related Questions