【问题标题】:how do I get keys from a nested dictionary? [duplicate]如何从嵌套字典中获取键? [复制]
【发布时间】:2021-09-03 00:05:52
【问题描述】:

考虑嵌套字典:

 mapSel={'lassoPoints': {'mapbox': [[-9.51, 38.96],    [-9.28, 38.78], 
[-9.24, 38.78],    [-9.22, 38.70],    [-9.29, 38.68],    [-9.25,
38.70],    [-9.32, 38.69],    [-9.38, 38.60]]},  'points': [{'curveNumber': 0,   
'location': 'Cascais',    'pointIndex': 152,    'pointNumber': 152,   
'z': 187.769},   {'curveNumber': 0,    'location': 'Oeiras',   
'pointIndex': 158,    'pointNumber': 158,    'z': 186.113},  
{'curveNumber': 0,    'location': 'Sintra',    'pointIndex': 159,   
'pointNumber': 159,    'z': 221.223}]}

第一个键“lassoPoints”并不重要。我只是想考虑 Key="points" 有一个“位置”列表或一个数据框,如:

 location
0 Cascais
1 Oeiras
2 Sintra

我试过用本尼迪克特:

安装:pip install python-benedict

from benedict import benedict
mapSel= benedict(mapSel, keypath_separator='.')
val = mapSel.get('points.location')
val

一无所获

【问题讨论】:

  • 您不能在get() 上使用点符号。每次通话都必须上一级,并且不能忘记中间的列表。
  • @DavitTovmasyan 这行不通。

标签: python dictionary nested


【解决方案1】:

为什么不直接使用pandas

>>> import pandas as pd
>>> df = pd.DataFrame(mapSel["points"])
>>> df
   curveNumber location  pointIndex  pointNumber        z
0            0  Cascais         152          152  187.769
1            0   Oeiras         158          158  186.113
2            0   Sintra         159          159  221.223

如果您只需要locations,那么您可以访问该特定列。

>>> df["location"]
0    Cascais
1     Oeiras
2     Sintra
Name: location, dtype: object

【讨论】:

    【解决方案2】:

    这是你想要的吗?

    mapSel={'lassoPoints': {'mapbox': [[-9.51, 38.96],    [-9.28, 38.78], 
    [-9.24, 38.78],    [-9.22, 38.70],    [-9.29, 38.68],    [-9.25,
    38.70],    [-9.32, 38.69],    [-9.38, 38.60]]},  
            'points': [{'curveNumber': 0,   
    'location': 'Cascais',    'pointIndex': 152,    'pointNumber': 152,   
    'z': 187.769},   {'curveNumber': 0,    'location': 'Oeiras',   
    'pointIndex': 158,    'pointNumber': 158,    'z': 186.113},  
    {'curveNumber': 0,    'location': 'Sintra',    'pointIndex': 159,   
    'pointNumber': 159,    'z': 221.223}]}
    
    print([elt['location'] for elt in mapSel['points']])
    # >>> ['Cascais', 'Oeiras', 'Sintra']
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      • 2020-01-26
      • 2021-05-10
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多