Build dict from list of pairs that is made from string

58 Views Asked by At

Say we have a string like

s = "a=b&c=d&xyz=abc"

I would like to get dictionary

{"a": "b", "c": "d", "xyz": "abc"}

This is one way how to achieve this:

dict([item.split("=") for item in s.split("&")])

This using generator is a bit better

dict(item.split("=") for item in s.split("&"))

Is there some more elegant way? I tried this to take advantage of new walrus operator but it does not looks any better:

{(pair := item.split("="))[0]: pair[1] for item in s.split("&")}

EDIT: I am looking for something single pass, without creating temporary list, or even one or more temporary tuples per item. Just building the dict directly... Would there be something along these lines?

2

There are 2 best solutions below

1
Saliou DJIBRILA On

From your example,

d = {u.split('=')[0]:u.split('=')[1] for u in s.split('&')}.

2
I'mahdi On

try this:

s = "a=b&c=d&xyz=abc"

lst = [z for y in s.split("&") for z in y.split("=")]
    
dct = {lst[i]: lst[i+1] for i in range(0, len(lst), 2)}

dct

output:

{'a': 'b', 'c': 'd', 'xyz': 'abc'}