I’m strucked in trying to shorten the keys of my dictionnary
d1
{'A0Z40': ['A14160,A14161,A14162,A14163,A14164,A14165,A14166'],
'A0Z41': ['A1403,A1407,A1408,A1409,A1410,A1411'],
'A0Z42': ['A1201,A1205', 'A12041,A12042,A12043,A12044,A12045,A12046'],
'A0Z43': ['A1101']}
And I’m tring to have this:
{'A0Z' : ['A14160,A14161,A14162,A14163,A14164,A14165,A14166'],['A1403,A1407,A1408,A1409,A1410,A1411'],
['A1201,A1205', 'A12041,A12042,A12043,A12044,A12045,A12046'], ['A1101']}
I ‘ve tried with a dctionnary comprehension
d = {k[:3] : v for k, v in d.items() }
but it erased the value since a dictionnary can only have unique keys…
If you have other solution ?
Thank you very much
>Solution :
You can do it with regular for loop using get and default value
d = {}
for k, v in d1.items():
d[k[:3]] = d.get(k[:3], []) + v
this will combine the lists in the values to one list under the key 'A0Z'
{'A0Z': ['A14160,A14161,A14162,A14163,A14164,A14165,A14166', 'A1403,A1407,A1408,A1409,A1410,A1411', 'A1201,A1205', 'A12041,A12042,A12043,A12044,A12045,A12046', 'A1101']}
If you would like to have the value as a list of lists just put the value v in a list in each iteration
d[k[:3]] = d.get(k[:3], []) + [v]
outout:
{'A0Z': [['A14160,A14161,A14162,A14163,A14164,A14165,A14166'], ['A1403,A1407,A1408,A1409,A1410,A1411'], ['A1201,A1205', 'A12041,A12042,A12043,A12044,A12045,A12046'], ['A1101']]}