[英]Adding results from a for loop to a dictionary , and then appending to a list
I'm aware that this is really simply , but I'm struggling with this. 我知道这真的很简单,但是我为此感到挣扎。 Basically I want to add the results of a for loop inside a dicionary, so i can work the results on another function, which i can print the desired field based on the key value,
基本上,我想在字典中添加for循环的结果,因此我可以将结果用于另一个函数,该函数可以根据键值打印所需的字段,
Example: 例:
i = 0
b = 0
cc = []
while True:
i += 1
b += 1
abc = {b: i}
cc.append(abc)
if i == 3:
break
Result : [{1: 1}, {2: 2}, {3: 3}]
结果:
[{1: 1}, {2: 2}, {3: 3}]
So, the expected result would be [{"1": 1, "2": 2, "3": 3}]
因此,预期结果将为
[{"1": 1, "2": 2, "3": 3}]
This is for python 2.7 这是针对python 2.7
Based on your expected outcome, I would suggest this: 根据您的预期结果,我建议这样做:
cc = []
for i in range(0,3):
cc.append({str(i): i})
But please note that you do NOT get a dictionary at the end of this loop... What you get is a list of dictionaries, each dictionary featuring only one key-value pair... [{'1':1},{'2':2}]
is not the same as {'1':1, '2':2}
and you will probably have problems using such a list of dictionaries. 但是请注意,在此循环结束时您没有得到字典...您得到的是字典列表,每本字典仅包含一对键值对...
[{'1':1},{'2':2}]
与{'1':1, '2':2}
,使用这样的字典列表可能会遇到问题。
So my guess is you want something more along the lines of this: 所以我的猜测是您想要更多类似的东西:
cc = dict()
for i in range(0,3):
cc[str(i)] = i
Please tell me if I misunderstood your problem or if you need more explanation for the solutions. 如果我误解了您的问题,或者您需要更多解决方案的解释,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.