根据不同的字典和键/值集创建多层字典-python

上下文:我生成了一个networkx图,其中包含不同的运输站点。每个站点的唯一属性是它们的idnamelonlat位置。

我想为每个点添加其他属性,这些属性可以在我以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'),...}

我想将Dict1Dict2Dict3链接到一个我打算在以后的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}一样打开三个csvdataframes,然后从中取出所需的merge,但是我不知道该怎么做要么。

zhaoyuan6677 回答:根据不同的字典和键/值集创建多层字典-python

我不确定是否要合并字典中的所有所有信息,或仅合并指定的停靠路线名称。对于后者,这是一些简单的代码,可使用

创建字典
  stop
    trip
      route

结构:

# initialise new dictionary
new_dict = {}

for stop in Dict2.keys():

    # access the "connection dict" and get the trip_id
    trip_ids = Dict1.get(stop).get('trip_id')

    # initialise trip dict
    trip_dict = {}

    # if there is only one trip_id,create a list with a single entry
    if not isinstance(trip_ids,list):
        trip_ids = [trip_ids]

    for trip_id in trip_ids:

        # using trip id,get route info:
        route_id = Dict3.get(trip_id).get('route_id')

        # combine information
        trip_dict[trip_id] = route_id

    new_dict[stop] = trip_dict

如果给定的stop_id具有多个trip_id,则new_dict将如下所示:

new_dict = {
       'stop_01': {
            'trip1': 'route1','trip2': 'route2' 
                  }
            }

您可以通过以下按键进行验证:

new_dict['stop_01'].keys()
本文链接:https://www.f2er.com/3158145.html

大家都在问