【问题标题】:Dictionary from a list of dictionaries字典列表中的字典
【发布时间】:2021-10-17 15:04:35
【问题描述】:

我有一长串这样的字典

`SymbolInfo =
{
 "time":1602832092060,
 "data":[
   {"id": "a", "symbol": "Name1", "high": "1.1", "last": "1"}
   {"id": "b", "symbol": "Name2", "high": "2.2", "last": "2"}
   {"id": "c", "symbol": "Name3", "high": "3.3", "last": "3"} 
   ...]
}`

我想从中获取包含一些特定值的元组字典,例如

mydict = {'a': '1.1', 'b':'2.2', 'c':'3.3', ...}

我正在尝试使用 foo 循环,但由于我对 python 还很陌生,所以我需要知道如何正确编写它。现在我有:

`mydict = {}
 for x in symbolInfo:
    prices['data'][x]['a'] = float(['data'][x]['high'])`

但我得到的错误是“TypeError: list indices must be integers or slices, not str”

有人可以帮帮我吗?非常感谢!

【问题讨论】:

  • 你需要遍历列表,而不是包含它的字典,所以for x in symbolInfo['data']: mydict[x['id']]=x['high']

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


【解决方案1】:

这将为您提供您指定的预期输出:

mydict = {d["id"]: float(d["high"]) for d in SymbolInfo["data"]}

但我不确定这是否是您想要的。您的帖子中有很多缺失的信息。什么是prices 变量?你说你想要一个元组的字典作为输出,但你给出的预期输出只是一个普通的字典?

【讨论】:

    【解决方案2】:

    你不需要遍历整个字典你只需要数据键 所以你也可以这样做:

    Dict = {}
    for x in SymbolInfo["data"]:
        Dict[x['id']]=x['high']
    

    【讨论】:

      猜你喜欢
      • 2019-01-14
      • 2014-10-15
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 2020-12-15
      相关资源
      最近更新 更多