我有一个元组列表,例如:
corp = [('h','somename'),
('h','someothername'),
('a','awholeothername'),
('a','name again'),
]
我希望创建一个字典,其中第一个索引h或a以
for x,y in corp:
if x == 'h':
x = 1
x = 0
但这似乎不起作用,因为我们无法在Python中进行项分配。将所有第0个索引映射到整数后
我尝试的是:
dicts = {'nationality': {} , 'name': {}}
for x,y in data:
dicts['nationality'] == x
dicts['name'] == y
但是不起作用。我通常远离字典,即使在两年的编码工作之后也是如此,这让我感到很不舒服
您可以使用
.items()
迭代字典的键和值:另外,请注意您应该使用一个
=
来完成作业要编辑列表,请找到要更改的索引并在分配中使用:
Imo(如果我正确理解了您的问题)一个非常好的
defaultdict
用例:产生
这样做的好处是,元组的第一个位置上可以有任何内容(它将产生一个
-1
)相关问题 更多 >
编程相关推荐