python - 如何创建字典的 array.array ?

标签 python arrays dictionary

字典的类型代码'x'是什么?

dict_array = array.array('x', [dict1, dict2, dict3])

我不知道在'x'处放什么。还有其他方法可以做到还是不可能?我不需要 dictlist,我想要它们的 array

最佳答案

一种技巧(仅适用于 CPython)是在数组中存储指向每个字典的指针:

import array
import _ctypes


def di(obj_id):
    """ Reverse of id() function. """
    # from https://stackoverflow.com/a/15012814/355230
    return _ctypes.PyObj_FromPtr(obj_id)


dict1 = {'key': '1'}
dict2 = {'key': '2'}
dict3 = {'key': '3'}

dict_array = array.array('q', map(id, [dict1, dict2, dict3]))

for i, ptr in enumerate(dict_array):
    print('dict_array[{}]: <0x{:08x}> {!r}'.format(i, ptr, di(ptr)))

输出:

dict_array[0]: <0x00946630> {'key': '1'}
dict_array[1]: <0x00946690> {'key': '2'}
dict_array[2]: <0x00d80660> {'key': '3'}

但是 @tobias_k 建议了一种更简单、更好(IMO)的方法,该方法使用整数字典键而不是内存指针。

以下是执行此操作的示例:

import array

dicts = {
    0: {'key': '1'},
    1: {'key': '2'},
    2: {'key': '3'},
}

dict_array = array.array('L', dicts.keys())

for i, key in enumerate(dict_array):
    print('dict_array[{}]: {!r}'.format(i, dicts[key]))

输出:

dict_array[0]: {'key': '1'}
dict_array[1]: {'key': '2'}
dict_array[2]: {'key': '3'}

关于python - 如何创建字典的 array.array ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695036/

相关文章:

python - (Python) 从大文件中切片行直到符号并附加到其他文件 - 最快的方法

python - Dockerfile 努力安装 Python Geopandas 模块

java - 为什么不能将 Object[] 转换为 String[]

javascript - 为什么 Array.prototype.fill() 与 `for` 循环相比有如此大的性能差异?

c# - 对象的哈希值如何存储在字典中?

python - 如何计算字典中某个键的对象数量?

python - 表格:FileNotFoundError:[Errno 2](但文件路径正确)

python - 我如何在 SQLAlchemy 中查询由 JSON 列过滤的数据?

ruby-on-rails - Ruby:根据 block 查找条件删除并返回数组值

python - 如何在不导入模块的情况下按值类型对字典进行排序