python - 如何将元组列表转换为字典
问题描述
我有一个元组列表,如下所示:
lst_of_tpls = [(1, 'test2', 3, 4),(11, 'test12', 13, 14),(21, 'test22', 23,24)]
我想将其转换为字典,使其看起来像这样:
mykeys = ['ones', 'text', 'threes', 'fours']
mydict = {'ones': [1,11,21], 'text':['test2','test12','test22'],
'threes': [3,13,23], 'fours':[4,14,24]}
我试图列举lst_of_tpls
这样的:
mydict = dict.fromkeys(mykeys, [])
for count, (ones, text, threes, fours) in enumerate(lst_of_tpls):
mydict['ones'].append(ones)
但这将我希望在“那些”中看到的值也放在其他“类别”中:
{'ones': [1, 11, 21], 'text': [1, 11, 21], 'threes': [1, 11, 21], 'fours': [1, 11, 21]}
另外,我想保持mykeys
灵活。
解决方案
您可以申请zip
两次以找到合适的配对:
lst_of_tpls = [(1, 'test2', 3, 4),(11, 'test12', 13, 14),(21, 'test22', 23,24)]
mykeys = ['ones', 'text', 'threes', 'fours']
new_d = {a:list(b) for a, b in zip(mykeys, zip(*lst_of_tpls))}
输出:
{
'ones': [1, 11, 21],
'text': ['test2', 'test12', 'test22'],
'threes': [3, 13, 23],
'fours': [4, 14, 24]
}
推荐阅读
- c++ - 引用指向类成员的指针时的 C++ 访问冲突
- android - 使用 Cordova ionic 管理多个构建变体 - Android 项目
- php - 使用 LIKE 子句的 MySql 搜索不起作用
- powershell - powershell有运行任务的能力吗?
- php - Doctrine MongoDB - 使用 Doctrine MongoDB Aggregation Builder 在构面内水合结果
- symfony - 在 symfony 3 中调用 null 上的成员函数 getId()
- excel - 如何使用 VBA 创建公式来引用单元格的动态偏移范围?
- php - 如果精确值匹配,则从 JSON 中删除数据?
- reactjs - 将 webpack 4 用于反应项目时模块解析失败
- javascript - IOS 的 Cordova Media Capture captureImage 崩溃