Python词典理解是否可以用Python(键)创建一个字典理解?如果没有列表理解,您可以使用以下内容:l = []for n in range(1, 11):
l.append(n)我们可以把它缩短为一个清单理解:l = [n for n in range(1, 11)].但是,假设我想将字典的键设置为相同的值。我能做到:d = {}for n in range(1, 11):
d[n] = True # same value for each我试过这个:d = {}d[i for i in range(1, 11)] = True但是,我得到了一个SyntaxError在for.此外(我不需要这个部分,只是想知道),您能为一组不同的值设置字典的键吗,如:d = {}for n in range(1, 11):
d[n] = n这与字典的理解是可能的吗?d = {}d[i for i in range(1, 11)] = [x for x in range(1, 11)]这也会引发SyntaxError在for.
3 回答

一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
>>> d = {n: n**2 for n in range(5)}>>> print d{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
>>> d = {n: True for n in range(5)}>>> print d{0: True, 1: True, 2: True, 3: True, 4: True}
oldDict.update(newDict)

九州编程
TA贡献1785条经验 获得超4个赞
dict.fromkeys
>>> dict.fromkeys(range(5), True){0: True, 1: True, 2: True, 3: True, 4: True}
d = dict.fromkeys(range(5), [])# {0: [], 1: [], 2: [], 3: [], 4: []}d[1].append(2)# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
defaultdict
from collections import defaultdict d = defaultdict(True)
{k: k for k in range(10)}
dict
defaultdict
__missing__
:
>>> class KeyDict(dict):... def __missing__(self, key):... #self[key] = key # Maybe add this also?... return key... >>> d = KeyDict()>>> d[1]1>>> d[2]2>>> d[3]3>>> print(d){}

catspeake
TA贡献1111条经验 获得超0个赞
>>> {i:i for i in range(1, 11)}{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
添加回答
举报
0/150
提交
取消