user12166681
user12166681

Reputation:

Changing list inside dictionary into sets?

For example, I have this that I opened from a .txt file:

{'fruit':['apple','pear'], 'veggies':['cucumber']}

How would I convert the items in the lists inside the whole dictionary into sets so it'll have the output:

{'fruit':{'apple','pear'}, 'veggies':{'cucumber'}}

Upvotes: 1

Views: 35

Answers (2)

wgb22
wgb22

Reputation: 247

If you iterate through the keys in the dict, you can cast the lists to sets.

d = {'fruit': ['apple', 'pear'], 'veggies': ['cucumber']}

for key in d.keys():
    s[key] = set(d[key])

This produces the output you want.

Upvotes: 0

John Gordon
John Gordon

Reputation: 33359

Iterate over all the keys in the dictionary, and reassign each key's value to be a set() of its current value:

for key in mydict:
    mydict[key] = set(mydict[key])

Upvotes: 1

Related Questions