[英]How to change a list into a dictionary
I am currently working with an API in python and trying to retrieve previous institution ID's from certain authors.我目前正在使用 python 中的 API 并尝试从某些作者那里检索以前的机构 ID。
I have come to this point我已经到了这一步
my_auth.hist_names['affiliation']
which outputs:输出:
[{'@_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'}]
The type here is list.这里的类型是列表。
I'd like to use this list as a dictionary to retrieve the '@id'
section我想将此列表用作字典来检索
'@id'
部分
One simple way to do this is to use list comprehension, which creates a new list based upon elements of an iterable.一种简单的方法是使用列表理解,它根据可迭代的元素创建一个新列表。 An implementation using this could be:
使用它的实现可能是:
ids = [item['@id'] for item in my_auth.hist_names['affiliation']]
This would create a list that contains each value associated with the @id
key.这将创建一个列表,其中包含与
@id
键关联的每个值。
You can simple load the list of dicts as dataframe with pandas您可以使用熊猫简单地将字典列表加载为数据框
import pandas as pd
my_auth.hist_names['affiliation']
df = pd.Dataframe(my_auth.hist_names['affiliation'])
print(df['@id'])
In this way you obtain a dataset in which every row is a dictionary of your list, and you can index by column your '@id'
通过这种方式,您可以获得一个数据集,其中每一行都是列表的字典,并且您可以按列索引
'@id'
with pd.Dataframe(my_auth.hist_names['affiliation']), you obtain使用 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...
and for df['@id'], your ids对于 df['@id'],您的 ID
0 60016491
1 60023955
2 109604360
3 112377026
4 112678642
5 60031106
Name: @id, dtype: object
The data is in JSON format, and you can use python's json library to process them.数据为JSON格式,可以使用python的json库进行处理。
https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/ https://www.geeksforgeeks.org/python-convert-string-dictionary-to-dictionary/
import json
result_dict = json.load(given_string)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.