【问题标题】:appending API request to another dictionary将 API 请求附加到另一个字典
【发布时间】:2022-06-17 23:20:58
【问题描述】:

我有一个应用程序,我需要从 API 请求中获取某些工作人员并将它们传递给另一个字典。字典的行为很奇怪,我似乎无法像普通列表或元组那样通过 +=.update 追加.

main.py

# worker_detail - contains a list of filtered workers
# workers - contains a list of all workers

information = {}
reported_workers = []
for person in workers:
    if person['id'] in worker_detail:
        reported_workers += person
        print(reported_workers)

如果我使用上述逻辑,它只会打印字典中的字段,而没有和工人..

['id', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job_id', 'salary', 'commission_pct', 'manager_id', 'department_id', 'id', 'first_name', 'last_name', 'email', 'phone_number', 'hire_date', 'job_id', 'salary', 'commission_pct', 'manager_id', 'department_id']

如果我 print(person) 输出将是包含所有必需字段及其详细信息的字典

{'id': 1, 'first_name': 'Steven', 'last_name': 'King', 'email': 'SKING', 'phone_number': 5151234567, 'hire_date': '2021-06-17', 'job_id': 'AD_PRES', 'salary': 24000, 'commission_pct': 0, 'manager_id': 0, 'department_id': 0}
{'id': 2, 'first_name': 'Neena', 'last_name': 'Kochhar', 'email': 'NKOCHHAR', 'phone_number': 5151234568, 'hire_date': '2020-06-17', 'job_id': 'AD_VP', 'salary': 17000, 'commission_pct': 0, 'manager_id': 100, 'department_id': 90}
{'id': 5, 'first_name': 'Bruce', 'last_name': 'Ernst', 'email': 'BERNST', 'phone_number': 5151234571, 'hire_date': '2016-07-17', 'job_id': 'IT_PROG', 'salary': 6000, 'commission_pct': 0, 'manager_id': 103, 'department_id': 60}
{'id': 9, 'first_name': 'Inbal', 'last_name': 'Amor', 'email': 'IMOR', 'phone_number': 5151234575, 'hire_date': '2013-08-23', 'job_id': 'IT_PROG', 'salary': 5000, 'commission_pct': 0, 'manager_id': 104, 'department_id': 60}

【问题讨论】:

  • reported_workers 是一个列表,而不是字典。

标签: python api


【解决方案1】:

append,不要+=

information = {}
reported_workers = []
for person in workers:
    if person['id'] in worker_detail:
        reported_workers.append(person)
print(reported_workers)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-31
    • 2022-07-18
    • 2021-03-04
    • 2018-10-13
    • 2020-09-13
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多