【问题标题】:Creating a multi-leveled dictionary from different dict and key/value sets - python从不同的字典和键/值集创建多级字典 - python
【发布时间】:2019-11-05 16:02:56
【问题描述】:

上下文:我生成了一个 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'),
              ('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')]), ...}

我想将Dict1Dict2Dict3 链接到一个多层次的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 打开为dataframesmerge,然后从中生成所需的dict,但我也不知道该怎么做。

【问题讨论】:

    标签: python dataframe dictionary networkx


    【解决方案1】:

    我不确定您是要合并字典中的所有信息,还是只合并您指定的停止行程路线名称。对于后者,这里有一些使用

    创建字典的简单代码
      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()
    

    【讨论】:

    • 感谢您的回答,理想情况下我想合并所有信息,但我将从 stop-trip-route 组合开始并从这里开始工作。您发布的内容只为每个 stop_id 提供了一个trip_id-route_id 组合,但是当stop_id 有多个时,我如何列出所有trip_is-route_id? (几乎总是如此)。
    • 你能更新一下问题吗?它更好地反映了数据?在那里,您只有一个旅行路线组合。
    • 我可以尝试但我在结果部分显示每个stop 可能有多个trip 与之相关(但每个trip 只有一个route 与之相关) .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2014-10-02
    • 2016-11-20
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多