简体   繁体   中英

adding a list to a dictionary in python 2.7

How do I add a list to a dictionary?

i have a dictionary:

>>> data = {}
>>> myfile='file.txt'
>>> data.update({myfile:['parama','y']})
>>> data
{'file.txt': ['parama', 'y']}

I would like to add to the key 'file.txt' another touple, such that the result would be

{'file.txt': (['parama', 'y'],['paramb','abc'])}

I tried to update this specific key like this:

data['file.txt'].update(['paramb','abc'])

but got an error:

Traceback (most recent call last):
  File "<pyshell#51>", line 1, in <module>
    data['file.txt'].update(['paramb', 'y'])
AttributeError: 'list' object has no attribute 'update'
>>> 

How do I add a list to a dictionary?

I think what you're after here is a dictionary whose keys are filenames, and whose values are themselves dictionaries whose keys are parameter names. Like this:

d = {
    'filename1': {
        'parama': 'A',
        'paramb': '22' },
    'filename2': {
        'parama': 'Z'}
}

This would allow you to access values like this:

>>> d['filename1']['parama']
'A'

And if you want to get all the parameters for filename1 :

>>> d['filename1']
{'parama': 'A', 'paramb': '22'}
>>> for k, v in d['filename1'].items():
...     print('{}: {}'.format(k, v))
parama: A
paramb: 22

If so, you're going wrote before you've gotten to the point you're asking about. Instead of this:

data.update({myfile:['parama','y']})

… you want:

data[myfile]['parama'] = 'y'

However, there's one slight problem here. If this is the first time you've seen a parameter for myfile , there is no data[myfile] yet. To solve that, you can use the setdefault method:

data.setdefault(myfile, {})['parama'] = 'y'

Or you can make data a collections.defaultdict(dict) instead of a plain dict .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM