I have the following dictionary on python:
dic = {1:'Ááa',2:'lol'}
if I printing it appears
print dic
{1: '\xc3\x81\xc3\xa1a', 2: 'lol'}
How can I obtain the following ouput ?
print dic
{1: 'Ááa', 2: 'lol'}
I have the following dictionary on python:
dic = {1:'Ááa',2:'lol'}
if I printing it appears
print dic
{1: '\xc3\x81\xc3\xa1a', 2: 'lol'}
How can I obtain the following ouput ?
print dic
{1: 'Ááa', 2: 'lol'}
You can not do that as the strings within data structure like dictionary or list printed by __repr__
method of string not __str__
. for more info read What is the difference between str and repr in Python
Return a string containing a printable representation of an object.
As an alternative you can convert the items to string and print them :
>>> print '{'+','.join([':'.join(map(str,k)) for k in dic.items()])+'}'
{1:Ááa,2:lol}
If you don't mind getting just the strings, without the enclosing quotes, you could iterate over the dict
and print out each key-value pair yourself.
from __future__ import print_function
for key, value in dict_.iteritems():
print(key, value, sep=': ', end=',\n')
If you're just going to print once, I would do this rather than building a string. If you want to do other things, or print them more than once, use Kasra's answer.
This does get confusing if the keys or values have colons, commas, or newlines in them, and the output won't be a valid Python literal, but it's the simplest way short of upgrading to Python 3.
I'm not sure if this is the best way to do what you want. I created a class to represent the data the way you wanted it. However you should note that a dictionary data type is no longer being returned. This is just a quick way to represent the data. The first line # -*- coding: utf-8 -*-
globally specifies the encoding type. So if you just want to be able to print your dictionary this will work.
# -*- coding: utf-8 -*-
class print_dict(object):
def __init__(self, dictionary):
self.mydict = dictionary
def __str__(self):
represented_dict = []
for k, v in self.mydict.items():
represented_dict.append("{0}: {1}".format(k, v))
return "{" + ", ".join(represented_dict) + "}"
dic = {1: 'Ááa', 2: 'lol'}
print print_dict(dic)
This works fine in python 3.
This is how it looks like when executed in python shell.
>>> dic={1: 'Ááa',2: 'lol'}
>>> print(dic)
{1: 'Ááa', 2: 'lol'}