在Python中将字典转换为以键作为对象名称的对象 [英] Converting dictionary to an object with keys as object's name in Python

查看:85
本文介绍了在Python中将字典转换为以键作为对象名称的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字典:

d = {'item1': ('Hi', (150, 495)), 'item2': ('Hola', (590, 40))}

我要尽可能将其转换为对象。我有一个班级:

I want to convert it to object, recursively if possible. I have a class:

class Item:
    def __init__(self,thetuple):
    self.greeting=thetuple[0]
    self.coordinate=thetuple[1]

那我想要的话,应该有一个对象,例如item1,而item1.greeting是 Hi,item1.coordinate是(150,495)等。

So what I want is, there should be an object, for instance item1, and item1.greeting is "Hi", item1.coordinate is (150,495) etc.

各种解决方案,改进,想法。谢谢。

I'm open to all kinds of solutions, improvements, ideas. Thanks.

推荐答案

您正在寻找 collections.namedtuple

You're looking for a collections.namedtuple.

这样做吧

import collections

Item = collections.namedtuple('Item', ('greeting', 'coordinate'))

d = {'item1': ('Hi', (150, 495)), 'item2': ('Hola', (590, 40))}

new_d = {k: Item(*v) for k, v in d.items()}

# Now you can do

new_d['item1'].greeting == 'Hi'

new_d['item2'].coordinate == (590, 40)

这篇关于在Python中将字典转换为以键作为对象名称的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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