【发布时间】:2019-11-05 16:02:56
【问题描述】:
上下文:我生成了一个 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'),
('stop_name', 'name2'),
('lat', 'lat2'),
('lon', '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'),
('t1', '18:14:00'),
('t2', '18:14:00')]), ...}
Dict3: ### Dict containing trip_id and route_id.
{'trip1': OrderedDict([('route_id', 'route1'),
('trip_id', 'trip1'),
('direction_id', '0')]),
'trip2': OrderedDict([('route_id', 'route2'),
('trip_id', 'trip2'),
('direction_id', '0')]), ...}
我想将Dict1、Dict2 和Dict3 链接到一个多层次的dict 中,然后我打算在nx.set_node_attributes() 中使用它。
对于Dict2 的每个stop_id,我想添加Dict3 中对应的每个trip_id。然后,对于之前添加的每个 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
...}
我知道在route_id 之前有trip_id 似乎不合逻辑,但我不会像trip_id 那样使用它,所以这个结果理论上应该让我未来的工作更容易。
我看过很多关于使用 python 创建嵌套字典的帖子,尤其是 this one 涉及多级字典,但我仍然找不到解决问题的方法,所以我在这里。
我总是可以将 3 个csv 打开为dataframes、merge,然后从中生成所需的dict,但我也不知道该怎么做。
【问题讨论】:
标签: python dataframe dictionary networkx