【问题标题】:Keeping the values separately in the dictionary with for loop in Python在 Python 中使用 for 循环将值分别保存在字典中
【发布时间】:2021-01-31 14:17:27
【问题描述】:

我在 StackOverflow 中查看了许多可能与我的问题有关的问题 Q1, Q2, Q3, Q4 它们都与我的问题无关。除此之外,我在这里检查了近 20 个问题。

我创建了一个示例代码块来简单地解释我的问题。我的目标是在 for 循环中将数据添加到字典中。

当我运行下面的代码块时,输出如下。

dictionary = defaultdict(int)

for uid in range(10):
    for i in range(5):
        distance = 2*i
        dictionary[uid] = distance

输出

我的目标是在每个循环中保留关键值并添加它。

预期输出:

{0: {0,2,4,6,8,}, 1:{0,2,4,6,8,}, 2:{0,2,4,6,8} , ...

我的解决方案

from collections import defaultdict

dictionary = defaultdict(int)
    
    for uid in range(10):
        for i in range(5):
            distance = 2*i
            dictionary[uid].append(distance)

我的解决方法也不起作用有问题

【问题讨论】:

  • 你只需要将你的默认字典类型声明为list 而不是int
  • 您需要它是list 还是set?预期输出显示set
  • dictionary = defaultdict(list)

标签: python dictionary for-loop


【解决方案1】:

试试这个:

from collections import defaultdict

dictionary = defaultdict(set)
for uid in range(10):
    for i in range(5):
        distance = 2*i
        dictionary[uid].add(distance)

输出 (dictionary):

> defaultdict(set,
            {0: {0, 2, 4, 6, 8},
             1: {0, 2, 4, 6, 8},
             2: {0, 2, 4, 6, 8},
             3: {0, 2, 4, 6, 8},
             4: {0, 2, 4, 6, 8},
             5: {0, 2, 4, 6, 8},
             6: {0, 2, 4, 6, 8},
             7: {0, 2, 4, 6, 8},
             8: {0, 2, 4, 6, 8},
             9: {0, 2, 4, 6, 8}})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多