【问题标题】:How to form a dictionary with different parameters?如何形成具有不同参数的字典?
【发布时间】:2014-08-18 21:43:52
【问题描述】:

我有一个带有类参数的class Test

parameters = {'first': [1,2,3,4], 'second': [5,6,7]}。我想把它转换成字典,这样它就是"{'Test': 'first':1 'second':5}"

我尝试的是: di = {} di = dict(itertools.izip(name, vals))

我在哪里得到测试,即变量名中的 classnane,即 name = Test

vals = {'first': [1,2,3,4], 'second': [5,6,7]} 虽然我想要它为"{'Test': 'first':1 'second':5}",但这不应该打印"{'Test': 'first':[1,2,3,4] 'second':[5,6,7]}"吗?相反,当我打印di 时得到的是{'Test': 'first'}。我不明白我的逻辑出了什么问题。

【问题讨论】:

    标签: python list class dictionary set


    【解决方案1】:

    使用dictionary comprehension

    subjects = ['Physics', 'Chemistry', 'Maths']
    {subject: {} for subject in subjects}
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Python 2,则可以使用 dict() 构造函数:

      subjects =  ['Physics', 'Chemistry', 'Maths']
      dict(((subject, {}) for subject  in subjects))
      

      如果您使用的是 Python 3,则可以使用dictionary comprehension

      subjects =  ['Physics', 'Chemistry', 'Maths']
      {subject: {} for subject in subjects}
      

      【讨论】:

      • 这个给出 TypeError: unhashable type: 'list'
      • 你使用的是 Python 2 还是 Python 3?
      • 2.7.7.我用 {subject: {} for subject in subject} 进行了尝试,即使使用 dict(((subject, {}) for subject in subject)) 仍然是同样的错误。
      • 它应该可以工作。我认为这个错误是指别的东西。也许您的主题列表中有嵌套列表?
      • 不,它不是嵌套列表。
      【解决方案3】:

      尝试使用字典理解:

      输入:

      {x: {} for x in ['Physics', 'Chemistry', 'Maths']}
      

      输出:

      {'Maths': {}, 'Chemistry': {}, 'Physics': {}}
      

      【讨论】:

      • 看起来 OP 希望这些项目是空字典——如果 OP 真的想要一个空字符串,那么 dict.fromkeys 是一个不错的选择。参考文献stackoverflow.com/q/14507591/748858
      • 对,我意识到了这一点。 dict理解是@mgilson问题的解决方案
      【解决方案4】:

      这是一个基本的 for 循环。 Itertools 对于这种东西来说是一种复杂的方式。

      >>> l = ['Physics', 'Chemistry', 'Maths']
      >>> d = {}
      >>> for i in l:
          d[i] ={}
      
      
      >>> d
      {'Chemistry': {}, 'Physics': {}, 'Maths': {}}
      

      【讨论】:

      • 嘿,我试过了,但我有一个问题,为什么它的顺序不同?而不是 {'Physics': {}, 'Chemistry': {}, 'Maths': {}} 为什么我们有 - {'Chemistry': {}, 'Physics': {}, 'Maths': {}} ??我需要做些什么才能使其按正确顺序排列?
      • 在 python 中,字典没有排序。如果你真的需要通过字典排序,只需使用for key in sorted(d):。附:这只是一个简单的 for 循环,其他答案更高效、更快且通常更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-06
      • 2022-01-19
      相关资源
      最近更新 更多