很抱歉没有分享详细信息,请看下面的代码*
import json
import requests
def funcname():
response = requests.get('https:aig.com/e/id')
parsed_response = json.loads(response.text)
print(parsed_response)
print(type(parsed_response))
如果我运行上面的代码,我得到以下输出:
{'values': [{'id': '123456','name': 'person1'}, {'id': '-1123678','name': 'person2'},{'id': '566','name': 'person3'}, {'id': '-1123678','name': 'person4'},{'id': '-1123678','name': 'person5'}]}
<class 'dict'>
实际上有100多个条目,我只列出了这5个
我想创建一个python程序来请求输入人名,并根据我们给出的名字打印id。
因此,假设我提示用户输入一个人的name
,用户输入person3
,那么输出应该是id566
不幸的是,提供的代码抛出了一个错误。
您可以根据您的输入构造一个字典并对其进行索引:
>>> myList = [{'id': '123','name': 'one'},{'id': '-1123','name': 'two'},{'id': '566','name': 'three'}]
>>> nameToId = dict((e['name'], e['id']) for e in myList)
>>> nameToId[input("Enter a name: ")]
Enter a name: two
'-1123'
你可以试试:
myDict = {'values': [{'id': '123456','name': 'person1'}, {'id': '-1123678','name': 'person2'},{'id': '566','name': 'person3'}, {'id': '-1123678','name': 'person4'},{'id': '-1123678','name': 'person5'}]};
for i in range(len(myDict['values'])):
if(myDict['values'][i]['name'] == 'person3'):
print(myDict['values'][i]['id'])
或
myDict = {'values': [{'id': '123456','name': 'person1'}, {'id': '-1123678','name': 'person2'},{'id': '566','name': 'person3'}, {'id': '-1123678','name': 'person4'},{'id': '-1123678','name': 'person5'}]};
name = input("Enter name: n")
for i in range(len(myDict['values'])):
if(myDict['values'][i]['name'] == name):
print(myDict['values'][i]['id'])
列表
mylist = [{'id': '123','name': 'one'},{'id': '-1123','name': 'two'},{'id': '566','name': 'three'}]
现在,假设你已经定义了一个变量
myname = "one"
您所要做的就是搜索具有该名称的相应id
:
[item["id"] for item in mylist if item["name"] == myname]
a = [{'id': '123','name': 'one'},{'id': '-1123','name': 'two'},{'id': '566','name': 'three'}]
name = input()
for i in a:
if i['name'] == name:
print(i['id'])
break