【问题标题】:Python: Looping and nested dictionariesPython:循环和嵌套字典
【发布时间】:2018-07-13 08:30:39
【问题描述】:

我有 3 个元组:

o = (0, 1)
n = ((1, 2), (1,))
c = ((30, 70), (20,))

我想放入嵌套字典中。期望的输出是:

{'0':{'1':30, '2':70}, '1':{'1':20}}

我尝试了以下方法:

for x in enumerate(o):
    graph[str(o[x])] = {}
    for y in enumerate(n):
        for z in enumerate(y):
            graph[str(o[x])][n[x][z]] = c[x][z]

这不起作用,我不知道如何继续。

【问题讨论】:

  • 请注意,(1)(20) 不是元组。
  • 如果将(1)(20) 制成元组,{ko: {kn:vc for kn, vc in zip(N, C)} for ko, N, C in zip(o, n, c)} 将起作用。即分别更改为(1,)(20,)
  • 抱歉 (1) 和 (20) 应该是元组 (1,) 和 (20,)。

标签: python python-3.x loops dictionary hash


【解决方案1】:

一个问题源于(1)(20) 不是元组(正如cmets 中的Ilja Everilä 所指出的那样)。由于它们实际上是int 类型,因此您不能迭代它们或使用[] 来索引。

首先是关于enumerate() 的注释,您使用不正确。这个函数返回一个 (index, value) 的元组。更多信息here

如果无法更改源数据,您可以稍微修改代码以获得所需的结果。像以前一样循环元组,但使用isinstance 检查元素是否为int

graph = {}
for i, x in enumerate(o):
    graph[x] = {}
    if isinstance(n[i], int):
        graph[x][n[i]] = c[i]
    else:
        for j in range(len(n[i])):
            graph[x][n[i][j]] = c[i][j]
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}

这段代码的else块可以进一步简化,使用zip()

graph = {}
for i, x in enumerate(o):
    graph[x] = {}
    if isinstance(n[i], int):
        graph[x][n[i]] = c[i]
    else:
        for y, z in zip(n[i], c[i]):
            graph[x][y] = z
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}

但是,更好的解决方案是将源数据 nc 更改为仅包含元组:

def make_tuple(x):
    return x if isinstance(x, tuple) else (x, )

new_n = map(make_tuple, n)
new_c = map(make_tuple, c)

那么上面的代码就不需要isinstance()检查了,可以简化为:

graph = {}
for i, x in enumerate(o):
    graph[x] = {}
    for y, z in zip(new_n[i], new_c[i]):
        graph[x][y] = z
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}

我们可以进一步简化为:

graph = {}
for ko, N, C in zip(o, new_n, new_c):
    graph[ko] = {}
    for kn, vc in zip(N, C):
        graph[ko][kn] = vc
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}

或者如果到紧凑的一个班轮(直接将上面的代码块翻译成字典理解):

graph = {ko: {kn:vc for kn, vc in zip(N, C)} for ko, N, C in zip(o, new_n, new_c)}
print graph
#{0: {1: 30, 2: 70}, 1: {1: 20}}

【讨论】:

  • @Bee,根据您的最新评论,我发现其中大部分不适用于您的问题。这对您有意义吗?或者您想进一步澄清吗?
  • 是的,现在一切都清楚了,非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-07-22
  • 2022-06-15
  • 2021-11-07
  • 2019-01-11
  • 2020-09-13
  • 1970-01-01
  • 2021-05-30
相关资源
最近更新 更多