上下文:我生成了一个networkx
图,其中包含不同的运输站点。每个站点的唯一属性是它们的id
,name
,lon
和lat
位置。
我想为每个点添加其他属性,这些属性可以在我以dicts
打开的3个csv文件中找到:(为了简化阅读,我对其进行了大量简化):
stops_csv = DictReader(open(STOPS_FILE,'r'))
Dict2 = dict()
for stop in stops_csv:
Dict2[stop['stop_id']] = stop
Dict2: ### Dict gotten from the nx graph.
{'stop1': OrderedDict([('stop_id','stop1'),('stop_name','name1'),('lat','lat1'),('lon','lon1')]),'stop2': OrderedDict([('stop_id','stop2'),'name2'),'lat2'),'lon2')]),...}
Dict1: ### Dict that links Dict2 and Dict3.
{'stop1': OrderedDict([('trip_id','trip1'),('t1','01:43:00'),('t2','01:43:00')]),'stop2': OrderedDict([('trip_id','trip2'),'18:14:00'),'18:14:00')]),...}
Dict3: ### Dict containing trip_id and route_id.
{'trip1': OrderedDict([('route_id','route1'),('trip_id',('direction_id','0')]),'trip2': OrderedDict([('route_id','route2'),...}
我想将Dict1
,Dict2
和Dict3
链接到一个我打算在以后的dict
中使用的单个多层nx.set_node_attributes()
中。
对于Dict2
的每个stop_id,我想添加trip_id
中对应的每个Dict3
。然后,对于先前添加的每个trip_id
,我想添加同样在route_id
中的每个Dict3
。
我的问题如下:
- 我似乎无法累积具有相同键的值而不是替换它们。
我尝试了建议的in this帖子,但似乎无法使其正常工作。所以我尝试了另一种方法,下面是我到目前为止所做的事情。基本上,每个
stop_id
都有一个或多个trip_id
对应,但是,我只得到最后一个trip_id
值。
test_dict = dict()
for s in Dict2: # 's' stands for stop.
test_dict['{}'.format(s)] = {}
for t in Dict3: # 't' stands for trip.
test_dict['{}'.format(s)]['trip_id'] = t
print(test_dict)
>>> {'stop1': {'trip_id': 'tripn'},#'tripn' corresponds to the last trip_id value.
'stop2': {'trip_id': 'tripn'},'stop3': {'trip_id': 'tripn'},'stop4': {'trip_id': 'tripn'},'stop5': {'trip_id': 'tripn'},...}
- 此外,我遇到的最大问题之一是
route_id
不是密钥,而是Dict3
的值,我也不知道该怎么做。因此,任何迹象在这里都将不胜感激...
结果应如下所示:
{stop1
trip1
route1
trip2
route1
stop2
trip3
route1
trip4
route1
trip5
route2
...}
我知道在trip_id
之前加上route_id
似乎不合逻辑,但我不会像trip_id
那样多地使用它,因此这种结果应该使我将来的工作更轻松理论。
我看过很多有关使用python创建嵌套词典的帖子,尤其是this one,它涉及到多级字典,但是我仍然找不到解决问题的方法,所以我在这里。
我总是可以像{{1}一样打开三个csv
,dataframes
,然后从中取出所需的merge
,但是我不知道该怎么做要么。