Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python创建列表字典_Python_Dictionary - Fatal编程技术网

Python创建列表字典

Python创建列表字典,python,dictionary,Python,Dictionary,我想创建一个值为列表的字典。例如: { 1: ['1'], 2: ['1','2'], 3: ['2'] } 如果我这样做: d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) 我得到一个键错误,因为d[…]不是一个列表。在本例中,我可以在赋值后添加以下代码来初始化字典 for x in range(1, 4): d[x]

我想创建一个值为列表的字典。例如:

{
  1: ['1'],
  2: ['1','2'],
  3: ['2']
}
如果我这样做:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d[j].append(i)
我得到一个键错误,因为d[…]不是一个列表。在本例中,我可以在赋值后添加以下代码来初始化字典

for x in range(1, 4):
    d[x] = list()
有更好的方法吗?比方说,在进入第二个
for
循环之前,我不知道我将需要的钥匙。例如:

class relation:
    scope_list = list()
...
d = dict()
for relation in relation_list:
    for scope_item in relation.scope_list:
        d[scope_item].append(relation)
另一种选择是替换

d[scope_item].append(relation)

处理这个问题的最佳方法是什么?理想情况下,追加将“起作用”。是否有某种方式可以表达我想要一个空列表字典,即使我在第一次创建列表时不知道每个键?

您可以使用:

名称相当奇怪的
setdefault
函数说“使用该键获取值,或者如果该键不存在,则添加该值,然后返回它。”


正如其他人正确指出的那样,
defaultdict
是一个更好、更现代的选择<代码>设置默认值在较旧版本的Python(2.5之前)中仍然很有用。

您可以使用如下列表理解来构建它:

>>> dict((i, range(int(i), int(i) + 2)) for i in ['1', '2'])
{'1': [1, 2], '2': [2, 3]}
对于问题的第二部分,使用

您可以使用:

>>从集合导入defaultdict
>>>d=默认DICT(列表)
>>>a=['1','2']
>>>对于我来说,在一个:
...   对于范围内的j(int(i),int(i)+2):
...     d[j].附加(i)
...
>>>d
defaultdict(,{1:['1'],2:['1',2'],3:['2']})
>>>d.项目()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

您的问题已经得到了回答,但IIRC您可以替换以下行:

if d.has_key(scope_item):
与:


也就是说,
d
引用了该构造中的
d.keys()。有时候,
defaultdict
不是最好的选择(例如,如果您想在与上述
if
关联的
else
之后执行多行代码),我发现
语法中的
更容易阅读。

就我个人而言,我只是使用JSON将内容转换为字符串并返回。我明白

import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}
简单的方法是:

a = [1,2]
d = {}
for i in a:
  d[i]=[i, ]

print(d)
{'1': [1, ], '2':[2, ]}

这是可行的,但如果有defaultdict,人们通常更倾向于使用它。@David,是的,setdefault不是最出色的设计,对不起,它几乎不是最好的选择。我确实认为我们(Python提交者)用collections.defaultdict挽回了我们的集体声誉;-)@DavidZ,setdefault与defaultdict不同,因为它更灵活:另外,您如何为不同的字典键指定不同的默认值?@AlexGidan没错,但与此问题不太相关。当您需要OrderedDict和默认值时,此答案也很有用。
collections
模块下的其他词典也以这种方式工作,例如
collections.OrderedDict
。哦。这太棒了。您不必初始化为“=[]”。好东西<代码>名称错误:未定义名称“a”
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]
if d.has_key(scope_item):
if scope_item in d:
import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}
a = [1,2]
d = {}
for i in a:
  d[i]=[i, ]

print(d)
{'1': [1, ], '2':[2, ]}