【问题标题】:How to transform a tuple into a dictionary?如何将元组转换为字典?
【发布时间】:2021-12-30 08:07:24
【问题描述】:

我需要有关元组列表的帮助。

我有下一个清单:

list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]

我需要将一个元组转换成字典并得到下一个结果:

list = [{'name':'x1', 'amount':'10'}, {'name':'x2', 'amount':'15'}, 
        {'name':'x3', 'amount':'35'}, {'name':'x4', 'amount':'55'}]

【问题讨论】:

标签: python list dictionary tuples


【解决方案1】:

您还可以在列表理解中使用 dict() 构造函数:

out = [dict(zip(['name','amount'], tpl)) for tpl in lst]

或者等效地,你也可以在map中使用dict()构造函数:

out = list(map(lambda tpl: dict(zip(['name','amount'], tpl)), lst))

输出:

[{'name': 'x1', 'amount': '10'},
 {'name': 'x2', 'amount': '15'},
 {'name': 'x3', 'amount': '35'},
 {'name': 'x4', 'amount': '55'}]

【讨论】:

    【解决方案2】:

    尝试嵌套字典理解。

    list_of_tuples = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
    result = [{'name': name, 'amount': amount} for name, amount in list_of_tuples]
    

    这相当于更冗长(但可能更具可读性)

    result = []
    for name, amount in list_of_tuples:
        d = {'name': name, 'amount': amount}
        result.append(d)
    

    【讨论】:

      【解决方案3】:
      list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
      
      _list = []
      for i in list:
          _list.append({"name":i[0],"amount":i[1]})
      
      print(_list)
      

      【讨论】:

      • 请记住,Stack Overflow 不仅仅是为了解决眼前的问题,而是为了帮助未来的读者找到类似问题的解决方案,这需要了解底层代码。这对于我们社区的初学者和不熟悉语法的成员来说尤其重要。鉴于此,您能否edit 您的答案包括对您正在做什么的解释以及为什么您认为这是最好的方法?
      【解决方案4】:

      你可以这样做:

      list = [('x1', '10'), ('x2', '15'), ('x3', '35'), ('x4', '55')]
      dic={}
      list2=[]
      for i in range(len(list)): 
          dic2={}
          dic2['name']=list[i][0]
          dic2['amount']=list[i][1]
          list2.append(dic2)
      

      结果:

      【讨论】:

      • 您的代码没有运行,请您仔细检查并编辑它吗?
      • 我现在忘记添加列表变量的初始化检查它但我在我的笔记本电脑上测试它并且它有效。
      猜你喜欢
      • 2016-03-11
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 2017-10-10
      • 2010-10-15
      相关资源
      最近更新 更多