我对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')}}
创建一个
d
字典:然后,在每个循环中,在主
^{pr2}$D
字典中创建一个新条目:但每次,
d
都指向同一个字典。您已经用d[i] = ....
更新了它在每个循环中的值,但它仍然保持相同的对象。在因此,当您打印}引用同一个dictionary对象,其值是您在上一个循环中给它的值。在
D
,D['KBFI']
和{用Python的说法,我们说
dict
对象是可变的:您可以在不创建新对象的情况下更改它们包含的内容。在为了获得您想要的行为,您可以在每个循环中创建一个新的
^{3}$d
:但是这次黑客攻击
locals()
真的很难看。。。您宁愿使用:或者,您可以保留一个键名和字段名之间的对应关系表,然后将代码重写为:
使用字典理解。在
相关问题 更多 >
编程相关推荐