将字典转换为namedtuple或其他可哈希的dict-like的Python方式? [英] Pythonic way to convert a dictionary into namedtuple or another hashable dict-like?

查看:138
本文介绍了将字典转换为namedtuple或其他可哈希的dict-like的Python方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字典

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

我想将其转换为namedtuple. 我目前的方法是使用以下代码

which I would like to convert to a namedtuple. My current approach is with the following code

namedTupleConstructor = namedtuple('myNamedTuple', ' '.join(sorted(d.keys())))
nt= namedTupleConstructor(**d)

产生

myNamedTuple(a = 1,b = 2,c = 3,d = 4)

myNamedTuple(a=1, b=2, c=3, d=4)

这对我来说很好(我认为),但是我是否缺少诸如...的内置功能

This works fine for me (I think), but am I missing a built-in such as...

nt = namedtuple.from_dict() ?

更新:正如评论中所讨论的,我想将字典转换为命名元组的原因是为了使其可散列,但仍像字典一样仍然可以使用.

UPDATE: as discussed in the comments, my reason for wanting to convert my dictionary to a namedtuple is so that it becomes hashable, but still generally useable like a dict.

推荐答案

要创建子类,您可以直接传递字典的键:

To create the subclass, you may just pass the keys of a dict directly:

MyTuple = namedtuple('MyTuple', sorted(d))

现在可以根据此字典或具有匹配键的其他字典创建实例:

Now to create instances from this dict, or other dicts with matching keys:

my_tuple = MyTuple(**d)

当心: namedtuple仅比较(有序).它们被设计为常规元组的替代品,具有命名属性访问作为附加功能. 进行相等比较时不会考虑字段名称.这不同于dict相等比较,后者确实考虑了键,并且可能不是您想要的,也不是namedtuple类型所期望的!

Beware: namedtuples compare on values only (ordered). They are designed to be a drop-in replacement for regular tuples, with named attribute access as an added feature. The field names will not be considered when making equality comparisons. This differs from dict equality comparisons, which do take into account the keys, and it may not be what you wanted nor expected from the namedtuple type!

如果只有一个字典,而不是一堆共享同一组键的字典,则首先没有必要创建此namedtuple.您应该只使用命名空间对象:

If you only have one dict, rather than a bunch of dicts sharing the same set of keys, then there is no point to create this namedtuple in the first place. You should just use a namespace object instead:

>>> from types import SimpleNamespace
>>> SimpleNamespace(**d)
namespace(a=1, b=2, c=3, d=4)

对于像食谱这样的可散列的"attrdict",请查看冻结的盒子:

For a hashable "attrdict" like recipe, check out a frozen box:

>>> from box import Box
>>> b = Box(d, frozen_box=True)
>>> hash(b)
7686694140185755210
>>> b.a
1
>>> b['a']
1

这篇关于将字典转换为namedtuple或其他可哈希的dict-like的Python方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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