【问题标题】:Create a dict from a list从列表中创建一个字典
【发布时间】:2023-04-08 03:00:01
【问题描述】:

我正在尝试使用 Python 2.7 从列表中创建字典

这是我的清单:

x = ['+proj=geos',
 'lon_0=86.5',
 'h=35785993.3373',
 'x_0=0',
 'y_0=0',
 'a=6378160',
 'b=6356775',
 'units=m',
 'no_defs ']

在我列表中的每个元素中,都有我的键和我的值,它们用字符“=”分隔。 结果,我想要这个:

d = {"+proj": "geos", "lon_0": "86.5", "h": "35785993.3373", "x_0": "0", "y_0": "0", "a": "6378160", "b": "6356775", "units": "m"}

【问题讨论】:

    标签: python python-2.7 list dictionary


    【解决方案1】:

    您可以将dict 与带有split 和过滤器的生成器表达式一起使用:

    >>> dict(y.split("=") for y in x if "=" in y)
    {'+proj': 'geos',
     'a': '6378160',
     'units': 'm',
     'b': '6356775',
     'y_0': '0',
     'x_0': '0',
     'h': '35785993.3373',
     'lon_0': '86.5'}
    

    【讨论】:

      【解决方案2】:

      试试这样的:

      d = {}
      for i in x:
          if '=' not in i: continue  # skip if no pair given
          key, value = i.split('=')  # split into pair
          d.update({key : value})    # update dict with pair
      

      【讨论】:

      • 我确认,它适用于 Python 2.7。非常感谢!
      • d.update 似乎有点不成比例。 d[key] = value 就足够了。
      • @Matthias 是的,你是对的,绝对更合适——仍然需要摆脱那个习惯
      猜你喜欢
      • 2020-08-31
      • 1970-01-01
      • 2019-11-29
      • 2016-02-14
      • 1970-01-01
      • 2018-09-18
      • 2021-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多