Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary with multiple string values for a key

I need a dictionary that is composed by a lot of keys, and the values must be a list that contains lots of strings. (in Python)

I tried:

d1[key].append(value)

but Python says:

AttributeError: 'str' object has no attribute 'append'.

I need something like : {a:[b,c,d,e],b:[t,r,s,z]....}

What could I do?

thanks in advance.

like image 493
Bruno A Avatar asked Feb 22 '26 01:02

Bruno A


1 Answers

You can use a collections.defaultdict:

>>> from collections import defaultdict
>>>
>>> d = defaultdict(list)
>>> d['key'].append(5)
>>> d
defaultdict(<type 'list'>, {'key': [5]})
>>> dict(d)
{'key': [5]}
like image 184
Rohit Jain Avatar answered Feb 24 '26 07:02

Rohit Jain