【问题标题】:How to change a list into a dictionary如何将列表更改为字典
【发布时间】:2020-10-24 22:38:18
【问题描述】:

我目前正在使用 python 中的 API,并尝试从某些作者那里检索以前的机构 ID。

我已经走到这一步了

my_auth.hist_names['affiliation']

哪个输出:

[{'@_fa': 'true',
  '@id': '60016491',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60016491'},
 {'@_fa': 'true',
  '@id': '60023955',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60023955'},
 {'@_fa': 'true',
  '@id': '109604360',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/109604360'},
 {'@_fa': 'true',
  '@id': '112377026',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/112377026'},
 {'@_fa': 'true',
  '@id': '112678642',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/112678642'},
 {'@_fa': 'true',
  '@id': '60031106',
  '@href': 'http://api.elsevier.com/content/affiliation/affiliation_id/60031106'}]

这里的类型是列表。

我想将此列表用作字典来检索 '@id' 部分

【问题讨论】:

  • 欢迎来到 SO。这不是讨论论坛或教程。请使用tour 并花时间阅读How to Ask 以及该页面上的其他链接。

标签: python json list dictionary


【解决方案1】:

您可以使用 pandas 将字典列表简单地加载为数据框

import pandas as pd
my_auth.hist_names['affiliation']
df = pd.Dataframe(my_auth.hist_names['affiliation'])
print(df['@id'])

这样你得到一个数据集,其中每一行都是你列表的字典,你可以按列索引 your'@id'

用 pd.Dataframe(my_auth.hist_names['affiliation']),你得到

   @_fa        @id                                              @href
0  true   60016491  http://api.elsevier.com/content/affiliation/af...
1  true   60023955  http://api.elsevier.com/content/affiliation/af...
2  true  109604360  http://api.elsevier.com/content/affiliation/af...
3  true  112377026  http://api.elsevier.com/content/affiliation/af...
4  true  112678642  http://api.elsevier.com/content/affiliation/af...
5  true   60031106  http://api.elsevier.com/content/affiliation/af...

对于 df['@id'],你的 ids

0     60016491
1     60023955
2    109604360
3    112377026
4    112678642
5     60031106
Name: @id, dtype: object

【讨论】:

    【解决方案2】:

    执行此操作的一种简单方法是使用list comprehension,,它根据可迭代的元素创建一个新列表。使用它的实现可能是:

    ids = [item['@id'] for item in my_auth.hist_names['affiliation']]
    

    这将创建一个列表,其中包含与 @id 键关联的每个值。

    【讨论】:

      【解决方案3】:

      数据是JSON格式的,可​​以使用python的json库来处理。

      https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/

      import json
      result_dict = json.load(given_string)
      

      【讨论】:

      • 我喜欢这个想法,但是,即使从字符串转换为列表时也会出错
      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 2019-03-29
      相关资源
      最近更新 更多