I have two lists:
list1=[0,0,0,1,1,2,2,3,3,4,4,5,5,5]
list2=['a','b','c','d','e','f','k','o','n','q','t','z','w','l']
dictionary=dict(zip(list1,list2))
I would like to output values of the same keys in one for each key such as it will print like this:
0 ['a','b','c']
1 ['d','e']
2 ['f','k']
3 ['o','n']
4 ['q','t']
5 ['z','w','l']
I wrote following code to do that but it does not work as I think
for k,v in dictionary.items():
print (k,v)
Could you tell me how to fix code so that I can get above intended results, please ? Thanks in advance!
Regarding your code:
dictionary = dict(zip(list1, list2))
creates the dictionary:
{0: 'c', 1: 'e', 2: 'k', 3: 'n', 4: 't', 5: 'l'}
which loses all but the last value in each group. You need to process the zipped lists to construct the grouped data. Two ways are with itertools.groupby() or with a defaultdict(list), shown here.
Use a collections.defaultdict of lists to group the items with keys from list1 and values from list2. Pair the items from each list with zip():
from collections import defaultdict
list1=[0,0,0,1,1,2,2,3,3,4,4,5,5,5]
list2=['a','b','c','d','e','f','k','o','n','q','t','z','w','l']
d = defaultdict(list)
for k,v in zip(list1, list2):
d[k].append(v)
for k in sorted(d):
print('{} {!r}'.format(k, d[k]))
Output:
0 ['a', 'b', 'c'] 1 ['d', 'e'] 2 ['f', 'k'] 3 ['o', 'n'] 4 ['q', 't'] 5 ['z', 'w', 'l']
Since items in a dictionary are unordered, the output is sorted by key.
The code you've shown does not look anything like what you described.
That aside, you can group values of the same key together by first zipping the lists and then grouping values of the same key using a collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
for k, v in zip(list1, list2):
d[k].append(v)
print(d)
# defaultdict(<type 'list'>, {0: ['a', 'b', 'c'], 1: ['d', 'e'], 2: ['f', 'k'], 3: ['o', 'n'], 4: ['q', 't'], 5: ['z', 'w', 'l']})
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