【问题标题】:How can I enter a dictionary inside an another empty dictionary?如何在另一个空字典中输入字典?
【发布时间】:2020-06-26 15:35:01
【问题描述】:

示例代码-

innerdict = {}
outerdict = {}
for line in range(1, 10, 2):
    for j in range(1, 10, 2):
        line_tuple = ("Item" + str( line ), int( line ))
        key = line_tuple[1]
        if line ==j:
           outerdict[key] = dict( innerdict )
           outerdict[key] = {'Name': '{0}'.format( "item"+str(j) ), 'Price': '{0}'.format( j )}
print(outerdict)

输出是这样的-

{1: {'Name': 'item1', 'Price': '1'}, 3: {'Name': 'item3', 'Price': '3'}, 5: {'Name': 'item5', 'Price': '5'}, 7: {'Name': 'item7', 'Price': '7'}, 9: {'Name': 'item9', 'Price': '9'}}

上述输出是可以实现的,因为它是常规的。我发现了很多关于嵌套字典理解的在线建议。

但我希望输出如下所示-

{{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'},  {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}

提前致谢!

【问题讨论】:

  • 你的意思是你想要一个集合而不是一个字典?还是清单?或者您只是希望您的打印输出看起来像这样?
  • 嗯,我想如果我可以将字典添加到一个列表中会更好。

标签: python-3.x nested dictionary-comprehension


【解决方案1】:

这是不可能的,因为 dict 对象不可散列。

{{1:2}} 意味着将字典{1:2} 放入set,由于上述对象的不可哈希性,这是不可能的。最好将它们放在一个列表中:

[{1:2}, {2:3}]

【讨论】:

  • 我可以把它们放在一个列表中。谢谢。
【解决方案2】:

你想要的是一个字典列表之类的东西。而这个{{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'}, {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}} 是无效的,因为字典被认为是一个键值对并且其中没有键。

可以通过将上面的内容分配给一个变量然后检查它的类型来检查它。

d = {{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'},  {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}
print(type(d))

这会导致一个错误,说它是不可散列的。

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    相关资源
    最近更新 更多