Change type of values in the dict (from list to set, from tuple...) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Change type of values in the dict (from list to set, from tuple...)

How do I change type of values in my dictionary? I can't figure out where do I make a mistake... For example, I need to have all the values as sets. D = {1: [("a", "b"), "c"], 2: ["mama", "papa"], 3: "apple"} D1 = dict () #create a new dict D1.update (D) #enter items from D to D1 for i in D1.values (): i = set (i) #this is supposed to change the type of all of the values to set print (D1.values()) print (D1) #I want to have this result: {1: {("a", "b"), "c"}, 2: {"mama", "papa"}, 3: {"apple"}}

7th Dec 2018, 4:32 PM
Daniella
Daniella - avatar
5 Answers
+ 2
The pattern you're looking for is: D[1] = set(D[1])
7th Dec 2018, 4:56 PM
HonFu
HonFu - avatar
+ 2
Yes, thank you, this one I have found... But was wondering, whether it's possible to do it through the loop, without indexing each key manually. When, for example, my dictionary has more than a dozen of items, wouldn't it be more logical to perform the loop iteration? Or it is impossible for this kind of task? Using the method d.values() and type change (x = set (x)).
7th Dec 2018, 9:54 PM
Daniella
Daniella - avatar
+ 2
Yes, you can use a for loop! for i in D: D[i] = set(D[i]) It looks just like with lists and in a practical sense it is: list items you access by index, dict items by key. EDIT: Sorry, messed up the names (repaired now). ^^'
7th Dec 2018, 10:06 PM
HonFu
HonFu - avatar
+ 2
Thank you very much! This one works perfectly ^^ Though I am still wondering why I can't access these values of the "i" with the d.values() method. Does it work then only for printing out the values? If so, it's not that practical. Anyway, it's great you've helped me to find out the answer, thanks :)
8th Dec 2018, 5:02 PM
Daniella
Daniella - avatar
0
Daniella, dict.values(), dict.items() and dict.keys() create separate objects, they are not the dictionary itself. You can use them when you want to access the material for the value (for example for printing them), but you can't directly change the content of the dictionary using them as far as I know. If I remember correctly, they change together with the dictionary whenever you modify it ('dynamic view'), so when you store for example the values object in a variable, you can use it together with the dictionary even while you change it. I haven't found much use for it myself yet. Mostly I use lists to move around stuff. Dictionaries are perfect when you want exactly what they do best: Access by key.
8th Dec 2018, 6:43 PM
HonFu
HonFu - avatar