"Exploding" (**myvariable) a dict with unicode keys

Samuel Wan sam at samuelwan.com
Tue Jun 2 19:44:40 EDT 2009

I started using python last week and ran into exceptions thrown when
unicode dictionary keys are exploded into function arguments. In my
case, decoded json dictionaries did not work as function arguments.
There was a thread from Oct 2008
(http://www.gossamer-threads.com/lists/python/python/684379) about the
same problem. Here is my workaround:

------------------ start code ---------------
def safe_dict(d):
	"""Recursively clone json structure with UTF-8 dictionary keys"""
	if isinstance(d, dict):
		return dict([(k.encode('utf-8'), safe_dict(v)) for k,v in d.iteritems()])
	elif isinstance(d, list):
		return [safe_dict(x) for x in d]
		return d

foo = {
	'b':{'b1':2, 'b2':3},
		{'D1':2, 'D2':3},
#generate and re-parse json to simulate dictionary with unicode keys
dictionary = json.loads(json.dumps(foo))

# shows unicode keys, like u"a"
print dictionary

# shows utf8 keys, like "a"
converted_dictionary = safe_dict(dictionary)
------------------ end code ---------------

I really like python! Hope this contributes to the thread.


 On Oct 3, 1:57 pm, Peter Otten <__pete... at web.de> wrote:
> "Martin v. Löwis" wrote:
> > Devin wrote:
> >> So Python can have unicode variable names but you can't
> >> "explode" (**myvariable) a dict with unicode keys? WTF?
> > That works fine for me.
> The OP probably means
> >>> def f(a=1): return a
> ...
> >>> f(**{"a": 42})
> 42
> >>> f(**{u"a": 42})
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: f() keywords must be strings
> Peter

Yes, that's exactly what I mean.

More information about the Python-list mailing list