Home > OS >  Convert string to dictionary with list of values
Convert string to dictionary with list of values

Time:11-10

What is the best way to convert a string to dictionary with value of dictionary as a list

for example str = "abc=1,abc=2,abc=3,xyz=5,xyz=6" i need the output as: d = {"abc":["1","2","3"],"xyz":["5","6"]}

I'm very new to python.

my code: d = {k: [v] for k, v in map(lambda item: item.split('='), s.split(","))}

CodePudding user response:

Here is the solution with dict.setdefault method.

>>> help({}.setdefault)
Help on built-in function setdefault:

setdefault(key, default=None, /) method of builtins.dict instance
    Insert key with a value of default if key is not in the dictionary.

    Return the value for key if key is in the dictionary, else default.

>>> your_str = "abc=1,abc=2,abc=3,xyz=5,xyz=6"
>>>
>>> result = {}
>>>
>>> for pair in your_str.split(","):
...     name, val = pair.split("=")
...     result.setdefault(name, []).append(val)

>>> result
{'abc': ['1', '2', '3'], 'xyz': ['5', '6']}

You could also use defaultdict with default factory as list

>>> from collections import defaultdict
>>>
>>> your_str = "abc=1,abc=2,abc=3,xyz=5,xyz=6"
>>>
>>> result = defaultdict(list)
>>> for pair in str.split(","):
...     name, val = pair.split("=")
...     result[name].append(val)
...
>>> dict(result)
{'abc': ['1', '2', '3'], 'xyz': ['5', '6']}

CodePudding user response:

The reason the code you have tried already isn't giving you the desired result is the fact that you are overwriting the value assigned to each key as you iterate over the list. What you need to do is append to the value already assigned to the key - except if the key doesn't exist, in which case you need to initialise that key.

This would be one way to go:

s1 = "abc=1,abc=2,abc=3,xyz=5,xyz=6"
list1 = [(each.split('=')) for each in s1.split(',')]
d = {}
for key, val in list1:
    if key in d.keys():
        d[key].append(val)
    else:
        d[key] = [val]
print (d)
#result: {'abc': ['1', '2', '3'], 'xyz': ['5', '6']}

You could simplify this and eliminate the if-else by using defaultdict, like so:

from collections import defaultdict

d = defaultdict(lambda: [])
    
s1 = "abc=1,abc=2,abc=3,xyz=5,xyz=6"

list1 = [(each.split('=')) for each in s1.split(',')]

for key, val in list1:
        d[key].append(val)
        
print (d)
#result: {'abc': ['1', '2', '3'], 'xyz': ['5', '6']}

CodePudding user response:

# initialize a dictionary
d = {}
# split the string (my_str) according to "," in order to get pairs such as 'abc/1' and 'xyz/5' in a list
for elt in my_str.split(",") : 
# for each string of the list, split according to '/' to get the pairs ['abc', 1]
# complete the dictionary 
    if elt.split('/')[0] not in d.keys():
        d[elt.split('/')[0]] = [elt.split('/')[1]]
    else : 
        d[elt.split('/')[0]].append(elt.split('/')[1])
  • Related