【发布时间】:2016-12-10 20:38:16
【问题描述】:
如果我这样做:
x1={'Count': 11, 'Name': 'Andrew'}
x2={'Count': 14, 'Name': 'Matt'}
x3={'Count': 17, 'Name': 'Devin'}
x4={'Count': 20, 'Name': 'Andrew'}
x1
vars=[x1,x2,x3,x4]
for i in vars:
my_dict[i[group_by_column]]=i
my_dict
然后我得到:
defaultdict(int,
{'Andrew': {'Count': 20, 'Name': 'Andrew'},
'Devin': {'Count': 17, 'Name': 'Devin'},
'Geoff': {'Count': 10, 'Name': 'Geoff'},
'Matt': {'Count': 14, 'Name': 'Matt'}})
这正是我想要的。
但是,当我尝试从内置 yield 的对象中复制它时,它会不断覆盖字典中的非常值。例如,cast_record_stream 是一个函数结果,可根据要求生成以下字典:
{'Count': 11, 'Name': 'Andrew'}
{'Count': 14, 'Name': 'Matt'}
{'Count': 17, 'Name': 'Devin'}
{'Count': 20, 'Name': 'Andrew'}
{'Count': 5, 'Name': 'Geoff'}
{'Count': 10, 'Name': 'Geoff'}
那么当我运行这个函数时,它就出现了错误:
for line in cast_record_stream:
record_name=line['Name']
my_dict[record_name]=line
defaultdict(<type 'int'>, {'Devin': {'Count': 10, 'Name': 'Geoff'},
'Matt': {'Count': 10, 'Name': 'Geoff'},
'Geoff': {'Count': 10, 'Name': 'Geoff'},
'Andrew': {'Count': 10, 'Name': 'Geoff'}})
我是否在这里制造了一个我看不到的问题?我认为它一次只会添加一个值。
【问题讨论】:
-
使用相关的
yield显示您的代码可能会有所帮助。 -
它是多个函数链接在一起,所以它只会让人感到困惑。重要的部分是它产生了我上面列出的每个字典,其中一些有重复的
Name -
我的猜测:
cast_record_stream修改并再次生成 相同 字典。确保在屈服之前创建一个新的字典。 -
不,如果我在调用最后一个循环后添加一行
print line,它将在每次迭代时生成不同的字典。 -
它会打印一个“不同”(看起来)的字典,因为您在打印之前没有更改它们。发布您的生成器函数,我大约 99.7% 确定这是问题所在。
标签: python dictionary nested