Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split List string and create dictionary

Tags:

python

I have this list:

lst= ['1 5','1 12','1 55','2 95', '2 66', '3 45',...]

As you can see each item consists of 2 numbers, second number is at most 4 characters long and they are separated by space.

I want to transfer that into dictionary like this

dct={1:{'doc0005','doc0012','doc0055'},2:{'doc0095','doc0066'},3:{'doc0045'},...}

each value item should be 7 characters long: 'doc'+someZeros+'second number from the list item, where someZeros are extra 0 characters to make value 7 characters long. And first number will be key of a dictionary

I was trying to split each item of a list and via loop adding it into dictionary, but i'm got confused

like image 895
Eric Klaus Avatar asked Sep 16 '25 16:09

Eric Klaus


1 Answers

This is easy to do with a (default)dictionary of sets.

from collections import defaultdict

d = defaultdict(set)
for l in lst:
     k, v = l.split()
     d[k].add(f'doc{int(v):04d}')  # "doc{:04d}".format(int(v))

print(d)
defaultdict(set,
            {'1': {'doc0005', 'doc0012', 'doc0055'},
             '2': {'doc0066', 'doc0095'},
             '3': {'doc0045'}})

If you'd prefer a plain dictionary, either dictify the result above, or use a slightly different (less efficient solution) using dict.setdefault:

d = {}
for l in lst:
    k, v = l.split()
    d.setdefault(k, set()).add(f'doc{int(v):04d}')  # "doc{:04d}".format(int(v))

print(d)
{'1': {'doc0005', 'doc0012', 'doc0055'},
 '2': {'doc0066', 'doc0095'},
 '3': {'doc0045'}}
like image 73
cs95 Avatar answered Sep 19 '25 06:09

cs95