+ 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}
7 Antworten
+ 7
https://code.sololearn.com/cSt6Zz0X5A3s/?ref=app
i was suprised this worked xD
+ 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
+ 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)
+ 2
thank ya bro , i'm working on it on my way 😂😂
+ 2
thank you ! 😎😎
+ 1
@Burey why the first method shows tow separated dictionnaries , but the second shows them matched ?
https://code.sololearn.com/cATIb42I66zH/?ref=app
+ 1
ah then the 2nd method matches them in one []
how can ii avoid the first method separation ?