最快的方式转换dict的键& `unicode`到`str`的​​值? [英] Fastest way to convert a dict's keys & values from `unicode` to `str`?

查看:139
本文介绍了最快的方式转换dict的键& `unicode`到`str`的​​值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个层代码接收到一个dict,在将其传递到另一个layer之前执行一些计算/修改。原来的dict的键& string的值是 unicode ,但是它们传递的层只接受 str

I'm receiving a dict from one "layer" of code upon which some calculations/modifications are performed before passing it onto another "layer". The original dict's keys & "string" values are unicode, but the layer they're being passed onto only accepts str.

这将被频繁调用,所以我想知道什么是最快的方式来转换类似:

This is going to be called often, so I'd like to know what would be the fastest way to convert something like:

{ u'spam': u'eggs', u'foo': True, u'bar': { u'baz': 97 } }

...至:

{ 'spam': 'eggs', 'foo': True, 'bar': { 'baz': 97 } }

...请注意,非字符串值需要保留为原始类型。

...bearing in mind the non-"string" values need to stay as their original type.

任何想法?

推荐答案

DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 },
         u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]}

def convert(data):
    if isinstance(data, basestring):
        return str(data)
    elif isinstance(data, collections.Mapping):
        return dict(map(convert, data.iteritems()))
    elif isinstance(data, collections.Iterable):
        return type(data)(map(convert, data))
    else:
        return data

print DATA
print convert(DATA)
# Prints:
# {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'}
# {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'}

假设:


  • 您已汇入collections模组,可以利用其提供的抽象基本类

  • 您很乐意使用默认编码(使用 data.encode('utf-8')而不是 str )如果您需要显式编码)。

  • You've imported the collections module and can make use of the abstract base classes it provides
  • You're happy to convert using the default encoding (use data.encode('utf-8') rather than str(data) if you need an explicit encoding).

如果您需要支持其他容器类型,明显如何遵循模式并为他们添加个案。

If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.

这篇关于最快的方式转换dict的键& `unicode`到`str`的​​值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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