【问题标题】:How do I handle a KeyError exception in python without exiting the dictionary?如何在不退出字典的情况下处理 python 中的 KeyError 异常?
【发布时间】:2019-11-13 19:52:19
【问题描述】:

基本上,我有一些 JSON 数据想要放入 MySQL 数据库中,为此我试图在 cursor.execute 方法中获取字典的内容。我的代码如下:

for p in d['aircraft']:
with connection.cursor() as cursor:
print(p['hex'])
sql = "INSERT INTO `aircraft` (`hex`, `squawk`, `flight`, `lat`, `lon`, `nucp`, `seen_pos`, " \
                          "`altitude`, `vert_rate`, `track`, `speed`, `messages`, `seen`, `rssi`) " \
                          "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )"

cursor.execute(sql, (p['hex'], p['squawk'], p['flight'], p['lat'], p['lon'], p['nucp'], p['seen_pos'], p['altitude'], p['vert_rate'], p['track'], p['speed'], p['messages'], p['seen'], p['rssi']))
print('entered')
connection.commit()

问题是字典中的任何值都可以随时为空,我需要找出如何处理这个问题。我尝试将代码放在 try catch 块中,并在引发 KeyError 异常时“通过”,但这意味着当记录具有空值时,它会被完全跳过。我还尝试编写大量 if 块来附加一个带有字典键值的字符串,但这毫无用处。

我需要找到一种方法将字典放入我的数据库中,即使它包含空值。

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    您可以使用dict.get() 方法,或构造一个defaultdict,它为缺少的键返回None

    import collections
    
    
    keys = ['hex', 'squawk', 'flight', 'lat', 'lon', 'nucp', 'seen_pos', 
            'altitude', 'vert_rate', 'track', 'speed', 'messages', 'seen',
            'rssi']
    
    for p in d['aircraft']:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `aircraft` (`hex`, `squawk`, `flight`, `lat`, `lon`, `nucp`, `seen_pos`, " \
                              "`altitude`, `vert_rate`, `track`, `speed`, `messages`, `seen`, `rssi`) " \
                              "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s )"
    
            # Could also use a defaultdict
            cursor.execute(sql, tuple(p.get(key) for key in keys))
            print('entered')
        connection.commit()
    

    有关使用dict.get() 的更多示例,请参阅此答案:https://stackoverflow.com/a/11041421/1718575

    这假设当提供None 时SQL 会做正确的事情。如果你想使用字符串'NULL',你可以将它作为第二个参数提供给dict.get()

    【讨论】:

    • 绝对完美。这正是我所需要的。感谢您的快速响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2020-01-31
    相关资源
    最近更新 更多