通过循环问题重命名字典键



在我的数据框架df中有一个列'EDU'。我尝试用value_counts(), poe_dict创建一个字典。它是这样的。

edu_m=df['EDU'].sort_values()
poe_dict = edu_m.value_counts(normalize=True).to_dict()
poe_dict
{4: 0.47974705779026877,
3: 0.24588090637625154,
2: 0.172352011241876,
1: 0.10202002459160373}

现在,我试着用我放在列表中的这些字符串替换键'4,3,2,1'。

n_keys=["college","高于高中但不高于大学","高中"低于高中"]

如果我单独执行它们,这运行正常,给出我预期的结果。

In:
poe_dict['college'] = poe_dict.pop(4)
poe_dict['more than high school but not college'] = poe_dict.pop(3)
poe_dict['high school'] = poe_dict.pop(2)
poe_dict['less than high school'] = poe_dict.pop(1)
Out:
{'college': 0.47974705779026877,
'more than high school but not college': 0.24588090637625154,
'high school': 0.172352011241876,
'less than high school': 0.10202002459160373}

但是,如果我尝试将它作为一个循环来执行,它会产生这个

In:
for key, n_key in zip(poe_dict.keys(), n_keys):
poe_dict[n_key] = poe_dict.pop(key)
poe_dict
Out:
{2: 0.172352011241876,
1: 0.10202002459160373,
'high school': 0.47974705779026877,
'less than high school': 0.24588090637625154}

所以我不明白为什么循环不工作键2和1?

我也试着调试它,看看像这样的循环中发生了什么。

In:
for key, n_key in zip(poe_dict.keys(), n_keys):

print (key,n_key)
poe_dict[n_key] = poe_dict.pop(key)

Out:
4 college
3 more than high school but not college
college high school
more than high school but not college less than high school

在for循环中遍历poe_dict的键。然而,当运行语句是poe_dict[n_key] = poe_dict.pop(key)时,poe_dict的键被修改。因此,密钥信息是错误的。正确的方法是将peo_dict的键存储到列表list(poe_dict.keys())中,然后循环遍历这个新的键列表。

poe_dict = {4: 0.47, 3:0.25, 2:0.17, 1:0.10}
n_keys = ['college', 'more than high school but not college','high school', 'less than high school' ]
keylist = list(poe_dict.keys())
for key, n_key in zip(keylist, n_keys):
print (key,n_key)
poe_dict[n_key] = poe_dict.pop(key)
print (poe_dict)

结果将是

{'college': 0.47, 'more than high school but not college': 0.25, 'high school': 0.17, 'less than high school': 0.1}

最新更新