【问题标题】:Convert list values to python dictionary将列表值转换为 python 字典
【发布时间】:2022-11-14 12:28:54
【问题描述】:

python列表到字典的转换

我们是一个 python 列表:

lst = ['aus:eng,sl','usa:eu,amc']

将python列表转换为字典=

dict={'aus':['eng','sl'],'usa':['eu','amc']}

dict 是我们想要的最终字典

python列表到字典的转换

【问题讨论】:

    标签: python list dictionary type-conversion element


    【解决方案1】:
    d_dict = dict()
    for i in lst:
        i = i.partition(':')
        d_dict.update({i[0]:i[2].split(',')})
    

    【讨论】:

    • 嗨,你是对的,但我们需要这种形式的结果:
    • dict={'aus':['eng','sl'],'usa':['eu','amc']}
    • 这次呢?
    【解决方案2】:
    {locale:countries.split(",") for locale, countries in map(lambda x: x.split(":"), lst)}
    
    {'aus': ['eng', 'sl'], 'usa': ['eu', 'amc']}
    

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2016-10-25
      • 2022-12-04
      • 2011-11-18
      • 2022-08-16
      • 1970-01-01
      相关资源
      最近更新 更多