【问题标题】:python lists of tuples to dictonary (MULTIPLE VALUES)python 元组列表到字典(多个值)
【发布时间】:2020-11-24 08:02:22
【问题描述】:

我想将元组列表转换为字典。 我想转换这个:

a=[('ram',1,"us"),("shyam",2,"np")]

到:

a={"ram":(1,"us"),"shyam":(2,"np")}

【问题讨论】:

  • 你尝试了什么?
  • {t[0]: t[1:] for t in a}…
  • 请提供你的努力。

标签: python list dictionary tuples


【解决方案1】:
a=[('ram',1,"us"),("shyam",2,"np")]

def convert(lst):
    dicto = {}
    for el in lst:
        dicto[el[0]]= (el[1], el[2])
    return dicto

print(convert(a))

输出:

{'ram': (1, 'us'), 'shyam': (2, 'np')}

【讨论】:

    【解决方案2】:
    a=[('ram',1,"us"),("shyam",2,"np")]
    d = {}
    for e in a:
        d[e[0]]= (e[1], e[2])
    print(d)
    

    输出:

    {'ram': (1, 'us'), 'shyam': (2, 'np')}
    

    【讨论】:

      【解决方案3】:
      def convert(lst):
          return {tup[0]:(tup[1:]) for tup in lst }
      
      a=[('ram',1,"us"),("shyam",2,"np")]
      
      
      print(convert(a))
      

      输出

      {'ram': (1, 'us'), 'shyam': (2, 'np')} 
      

      【讨论】:

      • tup[1:] 周围的() 是相当多余的……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多