String to dictionnary | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

String to dictionnary

how do i trasform a string with ":" into a dictionnary in python like a = "b : 1,c:2" be a_dict = {b:1,c:2}

20th Sep 2017, 9:17 PM
New Coder
New Coder - avatar
7 Antworten
+ 7
20th Sep 2017, 9:25 PM
Burey
Burey - avatar
+ 5
in the first method you create a new dictionary in each iteration you loop and each time assign a new dictionary to the variable, overwriting the old one
20th Sep 2017, 10:37 PM
Burey
Burey - avatar
+ 3
I was debating whether you might want to do the final step yourself and Burey posted, so here's what I was fiddling with FYI. # multi assignment a = "foo:bar" key,val = a.split(":") print(key,val) # list comprehension a = "foo:bar,biz:baz" myList = [entry for entry in a.split(",")] print(myList) # dictionary comprehension from list a = ["foo:bar"] myDict = {key:val for key,val in [entry.split(":") for entry in a]} print(myDict) # dictionary comprehension from string a = "foo:bar,biz:baz" dict = {key:val for key,val in [entry.split(":") for entry in a.split(",")]} print(dict)
20th Sep 2017, 9:40 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
thank ya bro , i'm working on it on my way 😂😂
20th Sep 2017, 9:27 PM
New Coder
New Coder - avatar
+ 2
thank you ! 😎😎
20th Sep 2017, 9:41 PM
New Coder
New Coder - avatar
+ 1
@Burey why the first method shows tow separated dictionnaries , but the second shows them matched ? https://code.sololearn.com/cATIb42I66zH/?ref=app
20th Sep 2017, 10:29 PM
New Coder
New Coder - avatar
+ 1
ah then the 2nd method matches them in one [] how can ii avoid the first method separation ?
20th Sep 2017, 10:39 PM
New Coder
New Coder - avatar