在For循环中创建字典时防止覆盖嵌套字典值

2024-06-11 19:23:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,正在尝试编写一个脚本,该脚本将遍历现有字典并重新组织数据,使其位于嵌套字典中。现有的字典是根据我在网上找到的一些代码创建的,这些代码将SQL查询中的一行转换为字典。我知道这有点多余,我只是不知道如何编辑这个代码,使它显示我想要的。在

脚本如下:https://geert.vanderkelen.org/2010/fetching-rows-as-dictionaries-with-mysql-connectorpython/

无论如何,当我这样做时,嵌套字典会自动覆盖以前的嵌套字典,即使嵌套字典的字典键正在更改。我已经搜索并找到了一些其他StackOverflow问题,但没有找到我的代码的解决方案。在

以下是我的相关代码:

    row=curs.fetchone
    d={}
    D={}
    while row is not None:
        station=row[u'STATION']
        date_obs=row[u'DATE_OBSERVATION']
        temperature=row[u'TMPC']
        altimeter=row[u'ALTM']
        dewpoint=row[u'DWPC']
        windspeed=row[u'SPED']
        winddirection=row[u'DRCT']
        for i in ('date_obs', 'temperature', 'altimeter', 'dewpoint', 'windspeed', 'winddirection'):
            d[i]=locals()[i]
        D[station]=d
        row = curs.fetchone()
print D

我会得到这样的结果(尽管有更多的字典条目):

{u'KBFI': {date_obs': datetime.datetime(2017, 7, 19, 16, 56), 'temperature': Decimal('21.00' 'dewpoint: 'Decimal('4.00'), 'altimeter': Decimal('30.10'), 'windspeed': Decimal('3.00'), 'winddirection': Decimal('310.00')}, u'KKLS': {date_obs': datetime.datetime(2017, 7, 19, 16, 56), 'temperature': Decimal('21.00' 'dewpoint: 'Decimal('4.00'), 'altimeter': Decimal('30.10'), 'windspeed': Decimal('3.00'), 'winddirection': Decimal('310.00')}}

想要一些像:

{u'KBFI': {date_obs': datetime.datetime(2017, 7, 19, 16, 53), 'temperature': Decimal('19.00' 'dewpoint: 'Decimal('5.00'), 'altimeter': Decimal('30.06'), 'windspeed': Decimal('4.00'), 'winddirection': Decimal('270.00')}, u'KKLS': {date_obs': datetime.datetime(2017, 7, 19, 16, 56), 'temperature': Decimal('21.00' 'dewpoint: 'Decimal('4.00'), 'altimeter': Decimal('30.10'), 'windspeed': Decimal('3.00'), 'winddirection': Decimal('310.00')}}


Tags: 代码脚本datetimedate字典rowdecimaltemperature
1条回答
网友
1楼 · 发布于 2024-06-11 19:23:31

创建一个d字典:

d = {}

然后,在每个循环中,在主D字典中创建一个新条目:

^{pr2}$

但每次,d都指向同一个字典。您已经用d[i] = ....更新了它在每个循环中的值,但它仍然保持相同的对象。在

因此,当您打印DD['KBFI']和{}引用同一个dictionary对象,其值是您在上一个循环中给它的值。在

用Python的说法,我们说dict对象是可变的:您可以在不创建新对象的情况下更改它们包含的内容。在

为了获得您想要的行为,您可以在每个循环中创建一个新的d

^{3}$

但是这次黑客攻击locals()真的很难看。。。您宁愿使用:

D={}

row = curs.fetchone
while row is not None:
    station = row[u'STATION']
    D[station] = {'date_obs': row[u'DATE_OBSERVATION'],
                  'temperature': row[u'TMPC'],
                  'altimeter': row[u'ALTM'],
                  'dewpoint': row[u'DWPC'],
                  'windspeed': row[u'SPED'],
                  'winddirection': row[u'DRCT']
                 }
    row = curs.fetchone()
print D

或者,您可以保留一个键名和字段名之间的对应关系表,然后将代码重写为:

fields = {'date_obs': u'DATE_OBSERVATION', 'temperature': u'TMPC'} # and so on...

D={}
row = curs.fetchone
while row is not None:
    station = row[u'STATION']
    D[station] = { key: row[field] for key, field in fields.items() }
    row = curs.fetchone()
print D

使用字典理解。在

相关问题 更多 >