在这种情况下,我想将所有字典键更改为大写。
我的字典看起来像这样:
dt = {' case_a':' EF57A48C',' case_b':{' case_b_a':5,' case_b_b& #39;:3},' case_c':{' case_c_a':{' case_c_a_a':1,' case_c_a_b':20,& #39; case_c_a_c':' sensor / pos / ss1',' case_c_a_d':0,' case_c_a_e':1},' case_c_b&# 39;:{' case_c_b_a':1,' case_c_b_b':-1,' case_c_b_c':' sensor / pos / ss2',& #39; case_c_b_d':99,' case_c_b_e':1},' case_c_c':{' case_c_c_a':2,' case_c_c_b&#39 ;:20,' case_c_c_c':' sensor / pos / ss1',' case_c_c_d':-1,' case_c_c_e':1}} }
功能:
def T_change(payload=dict()):
for key ,value in payload.items():
if isinstance(value,dict):
payload[str(key).upper()]=T_change(payload.pop(key))
else:
payload[str(key).upper()]=payload.pop(key)
return payload
执行:
T_change(DT)
结果:
{' CASE_A':' EF57A48C',' CASE_B':{' CASE_B_A':5,' CASE_B_B&#39 ;:3},' CASE_C':{' CASE_C_A':{' case_c_a_b ':20,' CASE_C_A_E&# 39;:1,' CASE_C_A_A':1,' CASE_C_A_C':' sensor / pos / ss1',' CASE_C_A_D':0}, ' CASE_C_B':{' case_c_b_b ':-1,' CASE_C_B_E':1,' CASE_C_B_A': 1,' CASE_C_B_C':' sensor / pos / ss2',' CASE_C_B_D':99},' CASE_C_C':{' case_c_c_b ':20,' CASE_C_C_E':1,' CASE_C_C_A':2,' CASE_C_C_C':'传感器/ pos / ss1',' CASE_C_C_D':-1}}}
我想将所有字典键更改为大写,但我不知道为什么函数会丢失某些键?
答案 0 :(得分:0)
当您执行 DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Python/2.7/site-packages/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Library/Python/2.7/site-packages/pip/req/req_set.py", line 778, in install
requirement.uninstall(auto_confirm=True)
File "/Library/Python/2.7/site-packages/pip/req/req_install.py", line 754, in uninstall
paths_to_remove.remove(auto_confirm)
File "/Library/Python/2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove
renames(path, new_path)
File "/Library/Python/2.7/site-packages/pip/utils/__init__.py", line 267, in renames
shutil.move(old, new)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 302, in move
copy2(src, real_dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 131, in copy2
copystat(src, dst)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 103, in copystat
os.chflags(dst, st.st_flags)
OSError: [Errno 1] Operation not permitted: '/tmp/pip-pId7ub-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/six-1.4.1-py2.7.egg-info'
时,您会更改字典的顺序,并且循环使用顺序工作。因此,当您弹出pop
时,它将在执行操作后成为dict的最后一个元素,case_c_a_a
将成为第一个。由于dict的第一个元素已经起作用,它将切换到下一个元素case_c_a_b
,而无需处理case_c_a_c
。要更好地理解它,请使用http://www.pythontutor.com/visualize.html
解决问题的方法是在函数中创建新的字典并使用return语句(也适用于递归调用)。这将解决问题。