如何在多个Python函数中更新同一字典以实现键值对累加
问题原因
- 代码中的
one()、two()仅完成了函数定义,没有被主动调用,修改字典的逻辑从未实际运行,因此输出的还是初始状态的字典。 - Python中函数定义阶段不会执行内部代码,只有调用函数时才会运行函数体中的逻辑。
调整方案
在打印字典前,依次调用两个修改函数即可,调整后的代码如下:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } def one(): thisdict['new1'] = 'newvalue1' return thisdict def two(): thisdict['new2'] = 'newvalue2' return thisdict # 调用两个修改字典的函数 one() two() print(thisdict)
运行后输出结果为:
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'new1': 'newvalue1', 'new2': 'newvalue2'}
优化建议
如果不想依赖全局变量,提升代码的可复用性,可以将字典作为参数传入函数:
def one(d): d['new1'] = 'newvalue1' return d def two(d): d['new2'] = 'newvalue2' return d thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict = one(thisdict) thisdict = two(thisdict) print(thisdict)
内容的提问来源于stack exchange,提问作者user29496
相关产品推荐
相关产品推荐

