使用Python在字典中创建或分配变量 [英] Creating or assigning variables from a dictionary in Python

查看:113
本文介绍了使用Python在字典中创建或分配变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在这里一次正常地问一个问题,但是没人知道我想问什么.因此,我在PHP中找到了示例.

I tried to ask a question normally once in here but nobody understands what I want to ask. So I've found example in PHP.

// $_POST = array('address' => '123', 'name' => 'John Doe');
extract($_POST);
echo $address;
echo $name

PYTHON中是否有类似extract()的功能???

is there's a function like extract() in PYTHON?????

字典也是如此:

mydict = {'raw':'data', 'code': 500}
// some magic to extract raw and code as vars
print raw 

p.s.我为什么要这样做:当您使用类方法时,当string为self.data ['raw'] ['code']时,很难对join()和format()中的字符串进行6种操作(假设这是这里的dict)

p.s. why I want to do this: when you're in class method, it's damned hard to have 6 manipulation with strings in join() and format() when string is self.data['raw']['code'] (assume it's dict in dict in here)

推荐答案

好吧php兄弟,所以这是个坏消息,python无法从空间不足的地方创建变量...就像php可以这样:$ {$ var}.使用local()是一个非常糟糕的主意,因为您将在调试中遇到很多问题,并且在那里已经定义了一些本地方法.所以这样做确实是一件坏事...

OK php brothers so here is a bad news, python can't create variables from out of space... like php can: ${$var} . To use local() is a very bad idea, because you'll have tons of problems with debugging, and there some locals already defined in there.. so it's really bad thing to do...

您无法像php一样以编程方式创建此代码.我认为这被称为非明确性,这是一个python通用名称:您总是知道变量名.在某些情况下,这种东西很容易自杀,您需要手工编写大量的vars ...主要是我对XML解析之类的东西感到不满意,但似乎有一些方法可以将python字典转换为类,我昨天被告知有关此信息,但仍未检查其工作方式(类似此处 )

You can't create this programmatically like php does. I think it's called non-explicity, and this is one python general: You ALWAYS know variable name. This kind of stuff just a suicide in some cases, you need to write by hand tons of vars... Mostly i was unhappy because of things like XML parsing, but it appears that there are method how to convert python dictionary into class, I was told about this yesterday but still haven't checked how it works ( something like here )

这篇关于使用Python在字典中创建或分配变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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