【问题标题】:Python - Save all data with a key missing or presentPython - 保存缺少或存在密钥的所有数据
【发布时间】:2022-11-02 23:27:27
【问题描述】:

我正在通过 api 检索数据,并且无论是否缺少密钥,我都想保存所有数据。

这是我的代码,它仅在密钥存在时才保存数据。

#get all of the initial users
initialUsers = requests.get(url, headers=headers)

data = initialUsers.json()



userData = data['data']


# write to a txt file
with open('Users.txt', 'x', encoding='utf-8') as f:
    for i in userData:
        if i.get('presence_id') is not None:
            sheet=(i['username']+" ",i['first_name']+" ", i['last_name']+" ", i['presence_id'])
            f.write(str(sheet)+"\n")

存在_id是有时存在的关键。

无论密钥是否存在,我如何修改它以保存所有数据?

【问题讨论】:

    标签: python


    【解决方案1】:

    不确定“即使不存在也保存所有数据”是什么意思。如果数据不存在,就没有什么可保存的了吗?我会戳一下,这个变量i 中可能存在一些其他键,这与presence_id 不同?然后我会这样解决它:

            # ...
            if i.get('presence_id') is not None:
                sheet=(i['username']+" ",i['first_name']+" ", i['last_name']+" ", i['presence_id'])
            else:
                sheet=""
                for other_key, other_val in i.values():
                    sheet += f"{other_key} had value: {other_val}"
            f.write(str(sheet)+"
    ")
                
    

    【讨论】:

      猜你喜欢
      • 2018-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多