防止在For循环中创建字典时嵌套字典值的覆盖
我对Python非常陌生,正在尝试编写一个脚本,该脚本通过现有字典循环并重新组织数据,以便它位于嵌套字典中。现有字典是根据我在线上找到的一些代码创建的,该代码将一行SQL查询转换为字典。我知道这有点多余,我只是不知道如何编辑这段代码来显示我想要的内容。防止在For循环中创建字典时嵌套字典值的覆盖
这里的脚本: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), '温度':十进制('21.00''露点:'十进制('4.00'), '高度计':十进制('30.10'),'windspeed':十进制('3.00'), 'winddirection':十进制('310.00')},u'KKLS':{date_obs': datetime.datetime (2017,7,19,16,56)“温度”:十进制('21.00' '露点:'十进制('4.00'),'高度计':十进制('30.10'), 'windspeed':十进制( '3.00'), 'winddirection':十进制( '310.00')}}
而想是这样的:
{u'KBFI ':{date_obs':datetime.datetime(2017年''.00''露点:'十进制('5.00'), '高度计':十进制('30 .06'),'windspeed':十进制(' 4.00'), 'winddirection':十进制('270.00')},u'KKLS':{date_obs': datetime.datetime(2017,7,19,16,56),'temperature':十进制('21 .00' '露点:'十进制('4.00'),'高度计':十进制('30.10'), '风速':十进制(' 3.00 '), 'winddirection':十进制(' 310.00' )}}
您创建一个d
字典有:
d = {}
然后,在每个循环中,将创建一个新词条D
字典与:
D[station] = d
但每一次,d
指的是非常相同的字典。您已使用d[i] = ....
更新了每个循环中的值,但它仍保持相同的对象。
因此,当您打印D
,D['KBFI']
和D['KKLS']
时,请引用相同的字典对象,其值是您在最后一次循环中给出的值。
用Python的说法,我们说dict
对象是可变的:你可以改变它们包含的内容而不需要创建一个新的对象。
为了得到你想要的行为,您可以创建在每个循环新d
:
while row is not None:
station = row[u'STATION']
# ....
d = {} # Here, we create a new dict
for i in ('date_obs', 'temperature', 'altimeter', 'dewpoint', 'windspeed', 'winddirection'):
d[i] = locals()[i]
D[station] = d # D[station] now refers to our new dict
但这个技巧与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
使用字典理解。
我看到的一个问题是您输入的字典无效。 ''''date_obs'''没有引号,'''Decimal('21 .00'''没有完全加上括号。 – user2233706