字典列表到/来自列表字典 [英] List of dicts to/from dict of lists

查看:37
本文介绍了字典列表到/来自列表字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在列表字典(长度相同)之间来回切换:

I am looking to change back and forth between a dictionary of lists (all of the same length):

DL = {'a': [0, 1], 'b': [2, 3]}

和字典列表:

LD = [{'a': 0, 'b': 2}, {'a': 1, 'b': 3}]

我正在寻找在两种形式之间切换的最简洁的方式.

I am looking for the cleanest way to switch between the two forms.

推荐答案

或许可以考虑使用 numpy:

Perhaps consider using numpy:

import numpy as np

arr = np.array([(0, 2), (1, 3)], dtype=[('a', int), ('b', int)])
print(arr)
# [(0, 2) (1, 3)]

这里我们访问按名称索引的列,例如'a''b'(有点像 DL):

Here we access columns indexed by names, e.g. 'a', or 'b' (sort of like DL):

print(arr['a'])
# [0 1]

这里我们通过整数索引访问行(有点像 LD):

Here we access rows by integer index (sort of like LD):

print(arr[0])
# (0, 2)

行中的每个值都可以通过列名访问(有点像LD):

Each value in the row can be accessed by column name (sort of like LD):

print(arr[0]['b'])
# 2

这篇关于字典列表到/来自列表字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆