【问题标题】:Convert list of dictionaries into list of sets?将字典列表转换为集合列表?
【发布时间】:2022-11-12 23:21:54
【问题描述】:

我在这样的列表中有字典:

[{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}]

期望的结果应该是这样的

[{'market', 'singapore', 'abbreviation', 'sg', 'indexId', 'STI', 'indexName', 'STRAITS TIMES INDEX'}, {'market', 'thailand', 'abbreviation', 'th', 'indexId', 'SET100', 'indexName', 'SET100 INDEX'}, {'market', 'turkey', 'abbreviation', 'tr', 'indexId', 'XUTEK', 'indexName', 'BIST TEKNOLOJI'}, {'market', 'thailand', 'abbreviation': 'th', 'indexId', 'SET50', 'indexName', 'SET50 INDEX'}]

我怎样才能删除这个字典列表中的“:”?我知道我可以使用re.sub() 函数,但我不知道如何在这种情况下应用它。

【问题讨论】:

  • 你所拥有的看起来像一个 JSON,你可以使用它来代替字符串列表。这样你就不会得到重复的“市场”、“缩写”等。

标签: python python-3.x


【解决方案1】:

这不是第一种形式的集合。那是一本字典。要将所有dict 的键和值放入一个集合中,您可以这样做:

>>> [set(list(i.keys()) + list(i.values())) for i in x]
[{'singapore', 'abbreviation', 'sg', 'STI', 'STRAITS TIMES INDEX', 'indexId', 'indexName', 'market'}, {'th', 'abbreviation', 'SET100 INDEX', 'thailand', 'indexId', 'SET100', 'indexName', 'market'}, {'BIST TEKNOLOJI', 'market', 'abbreviation', 'indexId', 'tr', 'XUTEK', 'indexName', 'turkey'}, {'th', 'SET50 INDEX', 'abbreviation', 'thailand', 'indexId', 'indexName', 'SET50', 'market'}]

x 是您的列表。

【讨论】:

    【解决方案2】:

    这些字符不是字符串的一部分,它们是由 print() 函数提供的格式。似乎您想将字典列表转换为列表列表。你可以通过列表理解来做到这一点:

    lst = [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}]
    
    res = [[item for sublist in dct.items() for item in sublist] for dct in lst]
    print(res)
    

    或者,您可以将其用于集合列表:

    lst = [{'market': 'singapore', 'abbreviation': 'sg', 'indexId': 'STI', 'indexName': 'STRAITS TIMES INDEX'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET100', 'indexName': 'SET100 INDEX'}, {'market': 'turkey', 'abbreviation': 'tr', 'indexId': 'XUTEK', 'indexName': 'BIST TEKNOLOJI'}, {'market': 'thailand', 'abbreviation': 'th', 'indexId': 'SET50', 'indexName': 'SET50 INDEX'}]
    
    res = [set([item for sublist in dct.items() for item in sublist]) for dct in lst]
    print(res)
    

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 1970-01-01
      • 2011-04-27
      • 2017-04-23
      • 2021-10-13
      • 2015-07-23
      • 1970-01-01
      • 2014-01-20
      相关资源
      最近更新 更多