'Transform list to the dictionary
I have a list with a strings ['scene-task-v001-user', 'scene-task-v002-user', 'scene-explo-v001-user', 'scene-train-v001-user', 'scene-train-v002-user']
strings created by regular expression
'(?P<scene>\w+)-(?P<task>\w+)-v(?P<ver>\d{3,})-(?P<user>\w+)'
I need to create dictionary where key its a task group and values contain all ver groups with the same task {'task': ['001', '002'], 'explo': ['001'], 'train': ['001', '002']}
How to do it?
Thanks!
Solution 1:[1]
First of all, ('t-1', 't-2', 's-1', 'z-1', 'z-2') is a tuple, not a list. In addition, {'t': {'1', '2'}, 's': {'1'}, 'z': {'1', '2'}} is wrong expression, a form of the values would be a list here, not {}. I corrected this issue in my codes below.
- Instead of using regular expression, you can loop the list and split by '-' inside the loop to get keys and values, as follows:
from collections import defaultdict
l = ('t-1', 't-2', 's-1', 'z-1', 'z-2')
d = defaultdict(list)
for item in l:
key, val = item.split('-')
d[key].append(val)
print(d) # defaultdict(<class 'list'>, {'t': ['1', '2'], 's': ['1'], 'z': ['1', '2']})
print(d['t']) # ['1', '2']
- Using regular expressions to get keys and values for a dictionary:
from collections import defaultdict
import re
l = ('t-1', 't-2', 's-1', 'z-1', 'z-2')
d = defaultdict(list)
for item in l:
key_patten = re.compile('\w-')
val_patten = re.compile('-\w')
key = key_patten.search(item).group().replace('-', '')
val = val_patten.search(item).group().replace('-', '')
d[key].append(val)
print(d) # defaultdict(<class 'list'>, {'t': ['1', '2'], 's': ['1'], 'z': ['1', '2']})
print(d['t']) # ['1', '2']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
