【问题标题】:How to convert a list of dictionaries, within a dictionary, to a list of just values? [duplicate]如何将字典中的字典列表转换为仅包含值的列表? [复制]
【发布时间】:2021-08-01 06:48:24
【问题描述】:

基本上我有一本看起来像这样的字典。

dictionary = { 'key': [ { 'key': 'value', etc.. } etc...] }

我想要一个仅包含“价值”的列表。我很新,所以我该怎么办?谢谢。

    dictionary = {
                   "candles":[
                              { 
                               "open": 78.21,
                               "high": 78.28,
                               "low": 78.12,
                               "close": 78.2,
                               "volume": 16417,
                               "datetime": 1620385200000
                               },
                               {
                                "open": 78.19,
                                "high": 78.26,
                                "low": 78.17,
                                "close": 78.2,
                                "volume": 5928,
                                "datetime": 1620387000000
                                }
                             [
                 }

【问题讨论】:

  • 请提供一些示例输入和输出。
  • @iota 当然,刚刚更新了帖子
  • 预期输出是什么?
  • @iota 基本上只是数字。 [78.21、78.28、78.12、78.2 等...]

标签: python python-3.x dictionary


【解决方案1】:

您可以使用嵌套的list comprehension

res = [val for l in dictionary.values() for d in l for val in d.values()]

Demo

【讨论】:

    【解决方案2】:

    也许:

    values = []
    for key in dictionary:
        for nested_dict in dictionary[key]:
            values += nested_dict.values()
    

    values 将是:

    [78.21, 78.28, 78.12, 78.2, 16417, 1620385200000, 78.19, 78.26, 78.17, 78.2, 5928, 1620387000000]
    

    【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多