I have a dict
:
JavaScript
x
5
1
dictionary = {'1': 'a',
2
'2': 'a',
3
'3': 'b',
4
'4': 'b'}
5
and I want to split it such that one dict
contains all items with value == 'a'
and the other one all items with value == 'b'
:
JavaScript
1
6
1
dict_a = {'1': 'a',
2
'2': 'a'}
3
4
dict_b = {'3': 'b',
5
'4': 'b'}
6
How can I do this in an short way? My approach
JavaScript
1
8
1
dict_a = {}
2
dict_b = {}
3
for key, value in dictionary.items():
4
if value == 'a':
5
dict_a = dict(key, value)
6
else:
7
dict_b = dict(key, value)
8
does not work.
Advertisement
Answer
Try this instead:
JavaScript
1
8
1
dict_a={}
2
dict_b={}
3
for key, value in dictionary.items():
4
if value == 'a':
5
dict_a[key] = value
6
else:
7
dict_b[key] = value
8
In your original code, you were recreating dict_a
or dict_b
every time you went through the loop.
If you’re not absolutely sure that your starting dict contains ONLY "a"
or "b"
values, use this instead:
JavaScript
1
10
10
1
dict_a={}
2
dict_b={}
3
for key, value in dictionary.items():
4
if value == 'a':
5
dict_a[key] = value
6
elif value == 'b':
7
dict_b[key] = value
8
else:
9
pass
10