how to print a dict which has japanese word using python - python

this is my code :
import xlrd,sys
data = xlrd.open_workbook('a.xls')
boss = data.sheets()[3]
print boss.row_values(3)[1]
it can show the right word :
キャプションサンプル。てすてす。改行もしたいよ
but because the a.xls has many data , so i append this data to a dict in python ,
like this :
stage_dict[stage_number]['boss'][boss_number]['name'] = boss_row_list[4]
and show it :
print stage_dict
but it show this :
'\uff77\uff6c\uff8c\uff9f\uff7c\uff6e\uff9d\uff7b\uff9d\uff8c\uff9f\uff99\u3002\u3066\u3059\u3066\u3059\u3002\u6539\u884c\u3082\u3057\u305f\u3044\u3088\u3002'
so what can i do ,
how to print a dict using the right Coding,
thanks
updated:
this is a simple demo :
#coding:utf-8
a={0:"キャプションサンプル。てすてす。改行もしたいよ"}
b="キャプションサンプル。てすてす。改行もしたいよ"
print a,b

You cannot. print(somedict) will always print the repr() of the dict which is valid python code using escape sequences.
However, since printing a dict should be a debug-only thing anyway this is not really a problem. Displaying a value from the dict should work.

You can derive your own class from dict and override __str__ method:
# -*- coding: utf-8 -*-
class MyDict(dict):
def __str__(self):
return "{"+", ".join(["%s: %s" % (key, self[key]) for key in self])+"}"
a = {0:"Velmi žluťoučký kůň"}
b = MyDict({0:"Velmi žluťoučký kůň"})
c = "Velmi žluťoučký kůň"
print(a)
print(b)
print(c)
Prints:
{0: 'Velmi \xc5\xbelu\xc5\xa5ou\xc4\x8dk\xc3\xbd k\xc5\xaf\xc5\x88'}
{0: Velmi žluťoučký kůň}
Velmi žluťoučký kůň
The derived class will behave exactly the same as dict, but it will print using the method you specify.

Printing an object in Python will print how the object is represented in English text. Hence the result you are experiencing.

Related

Unicode characters printed as escape sequences inside python object

I am using python 2.7.13. My python script generates a dictionary, which contains Hebrew.
The code is as follows,
# -*- coding: utf-8 -*-
val = "אבג".decode('utf-8')
print val
dict = {
'attributes' : {
'OBJECTID_1' : 1,
'LOCID' : val
}
}
print dict
The results are as follows,
אבג
{'attributes': {'LOCID': u'\u05d0\u05d1\u05d2', 'OBJECTID_1': 1}}
The first result shows as expected, since we use 'print'. However, in the dictionary I created, the Hebrew shows as unicode.
Is there anyway to display actual Hebrew in my dictionary? Or is this expected?
Thanks
In python2, when you print out a list, you end up printing the repr of the contents of that list.
In python3, a string's repr is the same as its str return value. You can observe this below:
Python2
>>> val = "אבג".decode('utf-8')
>>> val # displays repr value
u'\u05d0\u05d1\u05d2'
>>> print val # displays str value
אבג
And, as mentioned,
>>> print [val]
[u'\u05d0\u05d1\u05d2']
Constrasting with python3, str objects do not have a decode function - they are already decoded.
>>> val = "אבג"
>>> val
'אבג'
>>> print(val)
אבג
>>> print([val])
['אבג']
You can see this is why it works now.
For your problem, if you want to view the character as it is when you print the dict, you can do this:
print dict['LOCID']
Side note, do not use dict to name variables since it shadows the very important builtin class you are using.

how to create a dictionary from a set of properly formatted tuples in python

Is there a simple way to create a dictionary from a list of formatted tuples. e.g. if I do something like:
d={"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
This creates a dictionary called d. However, if I want to create a dictionary from a string which contains the same string, I can't do that
res=<some command that returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}>
print res
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
d=dict(res)
This throws an error that says:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I strongly strongly suspect that you have json on your hands.
import json
d = json.loads('{"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}')
would give you what you want.
Use dict(zip(tuples))
>>> u = ("foo", "bar")
>>> v = ("blah", "zoop")
>>> d = dict(zip(u, v))
>>> d
{'foo': 'blah', 'bar': 'zoop'}
Note, if you have an odd number of tuples this will not work.
Based on what you gave is, res is
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
So the plan is to grab the string starting at the curly brace to the end and use json to decode it:
import json
# Discard the text before the curly brace
res = res[res.index('{'):]
# Turn that text into a dictionary
d = json.loads(res)
All you need to do in your particular case is
d = eval(res)
And please keep security in mind when using eval, especially if you're mixing it with ajax/json.
UPDATE
Since others pointed out you might be getting this data over the web and it isn't just a "how to make this work" question, use this:
import json
json.loads(res)

Python 2.7.8: Printing a sub-dictionary value?

I'm using ConfigParser which returns a dictionary of configuration data as such:
{'general': {'UserKey': 'thisisatestkey'}}
If I want to simply print the value of the UserKey key (in this case thisisatestkey), then I generally just do a print "Your key is: {0}".format(mydictvar.get('UserKey')).
If I just print out the raw dict to a string I get the above. If I use the print statement above I get result of None since there is no key in the root of the dict called UserKey. If I .get('general') I just get: {'UserKey': 'thisisatestkey'}
Obviously I could do a fore loop like so:
keydic = cp.get_config_data()
for m, k in keydic.iteritems():
for s, v in k.iteritems():
userkey = v
and then print userkey which works fine. But I want to know how I can just avoid having to do the entire for loop first and just print the darned value right inline? Thanks!
You can use
mydictvar['general']['UserKey']
Or, if keys might be missing
mydictvar.get('general', {}).get('UserKey')
mydictvar['general'] returns a dictionary object; you can then just apply [...] to that value to retrieve the next key.
This works in string formatting too:
>>> mydictvar = {'general': {'UserKey': 'thisisatestkey'}}
>>> print "Your key is: {0[general][UserKey]}".format(mydictvar)
Your key is: thisisatestkey
simply without loop:
>>> my_dict = {'general': {'UserKey': 'thisisatestkey'}}
>>> my_dict['general']['UserKey']
'thisisatestkey'

How to modify the Python 'default' dictionary so that it always returns a default value

I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED".
I don't want to use d.get(key,default) but access dictionaries by d[key] so that if the key is not in d, it returns the default (that is same for all dictionaries).
I do not necessarily need to use dictionaries, but they were the intuitive choice...
Also, a dictionary where I could do this
d = {
1..16 = "RESERVED",
17 : "Foo",
18 : "Bar,
19..255: "INVALID"
}
Would be the preferred solution
Tuples could be another alternative, but then I'm prone to offset errors assigning the values... (and my code would not be "human readable")
Oh yeah, Python 2.4
If you can migrate to Python 2.5, there is the defaultdict class, as shown here. You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear.
If you can, use Mario's solution.
If you can't, you just have to subclass a dictionary-like object. Now, you can do that by inheriting directly from "dict", it will be fast and efficient. For old Python versions, with which you can't inherit from "dict", there is "UserDict", a pure Python dictionary implementation.
With it, you would do it this way :
#!/usr/bin/env python
# -*- coding= UTF-8 -*-
import UserDict
class DefaultDict(UserDict.UserDict) :
default_value = 'RESERVED'
def __getitem__(self, key) :
return self.data.get(key, DefaultDict.default_value)
d = DefaultDict()
d["yes"] = True;
print d["yes"]
print d["no"]
Keep in mind that "UserDict" is slower than "dict".
You can use the following class (tested in Python 2.7)
Just change zero to any default value you like.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)

How do you retrieve items from a dictionary in the order that they're inserted?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?
The standard Python dict does this by default if you're using CPython 3.6+ (or Python 3.7+ for any other implementation of Python).
On older versions of Python you can use collections.OrderedDict.
As of Python 3.7, the standard dict preserves insertion order. From the docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.
So, you should be able to iterate over the dictionary normally or use popitem().
Use OrderedDict(), available since version 2.7
Just a matter of curiosity:
from collections import OrderedDict
a = {}
b = OrderedDict()
c = OrderedDict()
a['key1'] = 'value1'
a['key2'] = 'value2'
b['key1'] = 'value1'
b['key2'] = 'value2'
c['key2'] = 'value2'
c['key1'] = 'value1'
print a == b # True
print a == c # True
print b == c # False
The other answers are correct; it's not possible, but you could write this yourself. However, in case you're unsure how to actually implement something like this, here's a complete and working implementation that subclasses dict which I've just written and tested. (Note that the order of values passed to the constructor is undefined but will come before values passed later, and you could always just not allow ordered dicts to be initialized with values.)
class ordered_dict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self._order = self.keys()
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
if key in self._order:
self._order.remove(key)
self._order.append(key)
def __delitem__(self, key):
dict.__delitem__(self, key)
self._order.remove(key)
def order(self):
return self._order[:]
def ordered_items(self):
return [(key,self[key]) for key in self._order]
od = ordered_dict()
od["hello"] = "world"
od["goodbye"] = "cruel world"
print od.order() # prints ['hello', 'goodbye']
del od["hello"]
od["monty"] = "python"
print od.order() # prints ['goodbye', 'monty']
od["hello"] = "kitty"
print od.order() # prints ['goodbye', 'monty', 'hello']
print od.ordered_items()
# prints [('goodbye','cruel world'), ('monty','python'), ('hello','kitty')]
You can't do this with the base dict class -- it's ordered by hash. You could build your own dictionary that is really a list of key,value pairs or somesuch, which would be ordered.
Or, just make the key a tuple with time.now() as the first field in the tuple.
Then you can retrieve the keys with dictname.keys(), sort, and voila!
Gerry
I've used StableDict before with good success.
http://pypi.python.org/pypi/StableDict/0.2
Or use any of the implementations for the PEP-372 described here, like the odict module from the pythonutils.
I successfully used the pocoo.org implementation, it is as easy as replacing your
my_dict={}
my_dict["foo"]="bar"
with
my_dict=odict.odict()
my_dict["foo"]="bar"
and require just this file
It's not possible unless you store the keys in a separate list for referencing later.
if you don't need the dict functionality, and only need to return tuples in the order you've inserted them, wouldn't a queue work better?
What you can do is insert the values with a key representing the order inputted, and then call sorted() on the items.
>>> obj = {}
>>> obj[1] = 'Bob'
>>> obj[2] = 'Sally'
>>> obj[3] = 'Joe'
>>> for k, v in sorted(obj.items()):
... print v
...
Bob
Sally
Joe
>>>

Categories