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
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 dict
ify 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'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With