【问题标题】:Creating a Dictionary from a Key List and Item List Based on the Order of the Elements in the Item List根据项目列表中元素的顺序从键列表和项目列表创建字典
【发布时间】:2019-05-25 22:41:36
【问题描述】:

看完这个问题后,我发现了解如何使用唯一列表作为项目和使用单数列表作为键很有帮助:Creating a dictionary with keys from a list and values as lists from another list 但是,我有列表,其中列表的第一个、第二个和其他元素需要按该顺序与键列表相关联。

问题是我已经尝试过该问题中描述的方法,但它没有考虑到主列表中每个列表中元素的顺序,以便将项目归因于我的字典的键。

key_list = ['m.title', 'm.studio', 'm.gross', 'm.year']
col = [['Titanic', '2186.8', 'Par.', '1997'], 
['The Lord of the Rings: The Return of the King', '1119.9', 'NL', '2003']]

我想要一个字典,其中 col 列表的项目根据元素在所有列表中出现的顺序归属于 key_list,并与 key_list 中元素的顺序相匹配。

期望的输出:{m.title:['泰坦尼克号', '指环王:王者归来'], 'm.studio':['2186.8', '1119.9'], 'm. Gross':['Par.', 'NL'], 'm.year':['1997', '2003']}

【问题讨论】:

  • 想要的输出是什么?
  • 你用 CSV 标记了这个,你是从 csv 文件中读取它吗?
  • 我用 csv 标记它,因为是的,但我还要将字典导出到 csv 文件。
  • @U9-Forward 我编辑了它

标签: python list csv dictionary dictionary-comprehension


【解决方案1】:

您要创建的对象列表可以使用嵌套在 List 理解中的 Dict 理解来创建:

[{key_list[idx]: val for idx, val in enumerate(row)} for row in col]

[{'m.year': '1997', 'm.gross': 'Par.', 'm.title': '泰坦尼克号', 'm.studio': '2186.8'}, {'m .year': '2003', 'm.gross': 'NL', 'm.title': '指环王:王者归来', 'm.studio': '1119.9'}]

编辑

对于{ key: List } 的字典:

dict(zip(key_list, [[row[idx] for row in col] for idx,_ in enumerate(key_list)]))

{'m.year': ['1997', '2003'], 'm.gross': ['Par.', 'NL'], 'm.title': ['泰坦尼克号', 'The指环王:王者归来], 'm.studio': ['2186.8', '1119.9']}

【讨论】:

  • 谢谢,这很有帮助,但为了澄清我的问题,我实际上是在寻找一本单数词典。这两年都是与 m.year 等相关的项目。我将编辑我的问题以澄清
【解决方案2】:

你可以dict(zip(...)):

print([dict(zip(key_list,values)) for values in col])

编辑:

print({k:list(zip(*col))[i] for i,k in enumerate(key_list)})

或者@MarkMeyer 的解决方案。

【讨论】:

  • @DataScienceAcolyte 会做
  • @DataScienceAcolyte 编辑了我的,但 Mark 的解决方案也不错。
【解决方案3】:

我不确定您是否真的需要列表或者是否可以使用元组。但是如果元组没问题,这非常简洁:

d = dict(zip(key_list, zip(*col)))

结果:

{'m.title': ('Titanic', 'The Lord of the Rings: The Return of the King'),
 'm.studio': ('2186.8', '1119.9'),
 'm.gross': ('Par.', 'NL'),
 'm.year': ('1997', '2003')}

【讨论】:

    猜你喜欢
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多