2015-05-12 61 views
-2

我想重新映射或将字典的键更改为1,2,3,...,因为键本身有点复杂。在这篇文章之后,How do I re-map python dict keys 这就是我所做的。尝试重新映射Python中字典的键时出现keyerror

tmp=0 
for keys in population.items(): 
     tmp+=1 
     population[tmp]=population.pop(keys) 

但是,我得到keyerrors,这通常意味着密钥不存在。任何人都可以帮助我吗? PS。我对字典中的项目进行了随机抽样。所以我不确定字典中的关键字是什么。

编辑:我改变了代码。然后它适用于小数据集,但对于大数据集并不适用。我添加了下面的代码。

for keys, vs in population.items(): 
     print str(keys)+ "corresponding to" + str(vs) 

Here is what I got: 
1024corresponding to10 
7corresponding to2 
855corresponding to4 
13corresponding to310 
686corresponding to6 
22corresponding to172 
24corresponding to214 
25corresponding to62 
26corresponding to18 
28corresponding to9 
29corresponding to435 
30corresponding to210 
32corresponding to243 
34corresponding to450 
859corresponding to8 
37corresponding to1 
689corresponding to3 
43corresponding to53 
46corresponding to8 
47corresponding to2 
48corresponding to7 
52corresponding to254 
54corresponding to441 
820corresponding to3 
57corresponding to19 
59corresponding to9 
61corresponding to3 
63corresponding to1 
65corresponding to1 
66corresponding to6 
(0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0)corresponding to7 
68corresponding to46842 
73corresponding to8 
74corresponding to513 
75corresponding to52 
866corresponding to10 
79corresponding to5 
80corresponding to712 
81corresponding to1 
82corresponding to118 
83corresponding to15 
84corresponding to9 
87corresponding to1 
88corresponding to7 
868corresponding to24 
93corresponding to133 
94corresponding to9 
97corresponding to355 
98corresponding to10 
99corresponding to9 
101corresponding to1 
103corresponding to93 
114corresponding to3 
702corresponding to5 
119corresponding to1 
121corresponding to1 
123corresponding to5 
124corresponding to3 
125corresponding to3 
819corresponding to5 
127corresponding to8 
131corresponding to137 
133corresponding to3 
138corresponding to145 
139corresponding to3 
142corresponding to14 
145corresponding to3 
147corresponding to6 
149corresponding to6 
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0)corresponding to1 

编辑编辑:我想改变所有的元组来表示人口字典的关键字。但是在我做出改变之后,然后打印出所有的键和值,它仍然给了我元组,就像你从打印出来的那样。

+0

“人口”是什么样的? – michaelpri

+2

请注意'.items()'不返回键列表。它返回'(key,value)'元组列表。有关更多信息,请参阅'pydoc dict'。 – larsks

+0

@michaelpri,人口将元组映射到一个整数。 – josephS

回答

0

只要删除.items(),这应该工作。正如larsks所说,items返回元组,但您只需要键。

1

dict.items()返回键/值对的列表(这就是为什么你想查找的元组,而不是关键的字典时KeyError错误),你需要的只是一个键:

tmp = 0 
for k in population.keys(): 
    tmp += 1 
    population[tmp] = population.pop(k) 

编辑:由于for k in dict迭代通过键生成器,所以当您同时修改键时可能会出现奇怪的行为。为了避免这种情况,我修改了代码来使用population.keys(),而不是返回一个键列表(在python2中)而不是键生成器。在python3 dict.keys()返回一个视图对象,而应该是安全的,只要在迭代过程中字典的大小不变(更安全地遍历list(population)

+0

实际上,在Python3中,这会返回一个View对象,而不是一个生成器。 – Olaf

0

我仍然不会拒绝这一点。你有一个字典,然后你将所有的值打包到一个列表中。由此你已经放弃了关键和价值之间的所有关系。那么字典的目的是什么?

但是,你似乎想(?还需要)来获取所有值的列表,你只是做:

my_list = list(my_dict.values()) 

无需环路或其他任何东西。