使用'defaultdicts'的Python程序不';I don’我没有按预期工作
预期结果:使用'defaultdicts'的Python程序不';I don’我没有按预期工作,python,Python,预期结果: main_dict = { 'a': { 0: 'Letter a', 1: 'Letter a', 2: 'Letter a',}, 'b': { 0: 'Letter b', 1: 'Letter b',
main_dict = {
'a':
{ 0: 'Letter a',
1: 'Letter a',
2: 'Letter a',},
'b':
{ 0: 'Letter b',
1: 'Letter b',
2: 'Letter b',},
'c':
{ 0: 'Letter c',
1: 'Letter c',
2: 'Letter c',}
}
我的程序,版本1;预期结果就是输出
# my_program.py
def fill_dict(a_dict, a_key):
if not a_dict.has_key(a_key):
a_dict[a_key] = {}
for i in xrange(3):
a_dict[a_key][i] = 'Letter {}'.format(a_key)
def main():
main_dict = {}
a_list = ['a', 'b', 'c']
for item in a_list:
fill_dict(main_dict, item)
if __name__ == '__main__':
main()
使用defaultdicts
重构程序;结果是main\u dict={}
# defaultdict_test.py
import collections
def fill_dict(a_dict, a_key):
a_dict = collections.defaultdict(dict)
for i in xrange(3):
a_dict[a_key][i] = 'Letter {}'.format(a_key)
def main():
main_dict = {}
a_list = ['a', 'b', 'c']
for item in a_list:
fill_dict(main_dict, item)
if __name__ == '__main__':
main()
有人指出我做错了什么吗?谢谢。您正在将
main\u dict
传递到fill\u dict
中,然后将新的defaultdict分配给局部变量a\u dict
。你永远不会把这个值传递出去
在运行的程序中,您不需要重新分配本地值,因此当您调用某个dict上的方法时,您需要修改传入的值,这是main中的main dict值
这种重新分配和方法变异之间的区别是微妙但重要的。本文详细介绍了名称、值及其交互:。指针:
的has_key
进行了删除fill\u dict
main\u dict={}
更改为main\u dict=collections.defaultdict(dict)
inmain
>>> {c:{i: 'Letter {}'.format(c) for i in range(3)} for c in 'abc'}
{'a': {0: 'Letter a', 1: 'Letter a', 2: 'Letter a'}, 'c': {0: 'Letter c', 1: 'Letter c', 2: 'Letter c'}, 'b': {0: 'Letter b', 1: 'Letter b', 2: 'Letter b'}}
如果你看它,它几乎是你想要的结果的一个版本,如果你这样格式化它:
dict_you_want={
c:
{ i: 'Letter {}'.format(c)
for i in range(3) } # ,
for c in 'abc'
}
这将像我在那里一样执行…顺便说一句:你应该修复你的缩进,因为你的for循环没有正确的主体。很抱歉。dawg已经修复了:)顺便说一句:如果一个密钥不在目录中,你应该使用
,
vs如果一个密钥不在目录中,你应该使用。如果没有一个密钥(一个密钥):
@dawg是的。这是(一个实际的)旧代码的例子,我正在逐步重构它。
dict_you_want={
c:
{ i: 'Letter {}'.format(c)
for i in range(3) } # ,
for c in 'abc'
}