简体   繁体   English

在python 2.7中向字典添加列表

[英]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 我想将另一个touple添加到键“ file.txt”中,这样​​结果将是

{'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 : 如果要获取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. 如果这是您第一次看到myfile的参数,则还没有data[myfile] To solve that, you can use the setdefault method: 为了解决这个问题,可以使用setdefault方法:

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

Or you can make data a collections.defaultdict(dict) instead of a plain dict . 或者,您可以将data collections.defaultdict(dict)而不是普通dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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