【问题标题】:How to get a list of lists from a dictionary of dictionaries in python?如何从python中的字典字典中获取列表列表?
【发布时间】:2020-03-26 10:46:35
【问题描述】:

我想将字典转换为列表列表。字典的格式是:

{0: {’apple’: 2, ’orange’: 5, ’banana’: 4}, 1: {'apple’: 2, ’orange’: 1, ’banana’: 7}}

键从 0、1、2、3 等... 字典中键的值是该水果的数量。我正在尝试制作一个如下所示的列表:

 [[2, 5, 4], [2, 1, 7]]

每个子列表都是原始键(0,1,2,3 等...)。因此,如果有 4 个字典,则有 4 个子列表。

我更喜欢没有花哨的代码和导入。我该怎么做呢?任何帮助将不胜感激!

【问题讨论】:

  • 看看下面的答案,几乎就像无序的字典从未存在过......当然,OP 的字典的键创建顺序完全正确,我们都知道,对吧?它们不可能以任何其他顺序创建/s
  • 没有迹象表明订单很重要@Aran-Fey。

标签: python python-3.x list dictionary converters


【解决方案1】:
x = {0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}


print([list(z.values()) for y,z in x.items()])

【讨论】:

    【解决方案2】:

    您可以使用values() 在简单的列表理解中做到这一点:

    myDict = {0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}
    
    arr = [list(d.values()) for d in myDict.values()]
    #[[2, 5, 4], [2, 1, 7]]
    

    【讨论】:

    • 这太棒了!谢谢你。有没有办法在没有列表理解的情况下做到这一点?因为我不熟悉它。
    • 列表推导是在 python 中执行此操作的方法。另一种方法是创建一个列表并在 for 循环中添加每个列表。
    【解决方案3】:
    x={0: {'apple': 2, 'orange': 5, 'banana': 4}, 1: {'apple': 2, 'orange': 1, 'banana': 7}}
    lst=[]
    lst1=[]
    for key,iteam in x.items():
        for k,itm in iteam.items():
            lst.append(itm)
        print(lst)
        lst1.append(lst)
        lst=[]  
    

    亲爱的没问题?

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      相关资源
      最近更新 更多