开发者

how to: convert dictionary to strings in Python? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Creating or assigning variables from a dictionary in Python

Hello

we have dictionary like this:

data = {'raw':'lores ipsum', 'code': 500}

how to convert this dict to strings? result must be like this:

print raw
print code
#output is 
#  lores ipsum
#  500

EDIT: OK, so what I want is to have raw and code variable available.. one more example

data = {'raw':'lores ipsum', 'code': 500}
var1 = code
var2 = raw

it's becomes difficult to make tons of string operations with variable, which is dict, which is in class method... so it's endups with this: self.data[开发者_JAVA技巧'raw'][0] , it's killing me to write this everytime so to make "raw" variable is more comfortable... (imagine join and format operation with using this on every line!!!) anyway this vars will be available only in this method, so there's no side-effects for this solution...

EDIT: deleted, nobody understands what I want


This is a pretty bad idea - using dicts as intended ends up with a much less confusing solution.

A quick hack dirty way of making the key=value pairs into non-dict string variables is as follows:

for key in data:
  exec("{0} = '{1}'".format(key,data[key]))

This is fragile and breaks with complex data types, aside from being ill-advised, but it does what you've asked.


Python Tutorial, §5.5, "Dictionaries"

print data['raw']
print data['code']


Very unclear to me what you exactly want, if you just want to print out the value of some dict key:

>>> print data['raw'] # etc
lores ipsum

will do the job.

If you want to print out all the keys, simple iterate over them:

for k, v in data.iteritems():
    print v

# ouput
# lores ipsum
# 500

But keep in mind that the dict is unordered, that means, the order of the output is not necessarily the order in which you declared the items.


Python local and globals variable are just kept in dicts as well. You just have to take one of these dicts, through the locals() or globals() function and update it.

It works, be warned it is not safe if you are getting this data from an external source, as any name on your environment (including those of built in functions) can be overriden this way.

>>> data = {'raw':'lores ipsum', 'code': 500}
>>> locals().update(data)
>>> print raw
lores ipsum
>>> print code
500
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜