在python中用urlencode多维字典 [英] urlencode a multidimensional dictionary in python

查看:259
本文介绍了在python中用urlencode多维字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中获得多维字典的URL编码版本?不幸的是,urllib.urlencode()仅在一个维度上起作用.我需要一个能够递归编码字典的版本.

How can I get a URL-encoded version of a multidimensional dictionary in Python? Unfortunately, urllib.urlencode() only works in a single dimension. I would need a version capable of recursively encoding the dictionary.

例如,如果我有以下字典:

For example, if I have the following dictionary:

{'a': 'b', 'c': {'d': 'e'}}

我想获取以下字符串:

a=b&c[d]=e

推荐答案

好的.我自己实现了:

import urllib

def recursive_urlencode(d):
    """URL-encode a multidimensional dictionary.

    >>> data = {'a': 'b&c', 'd': {'e': {'f&g': 'h*i'}}, 'j': 'k'}
    >>> recursive_urlencode(data)
    u'a=b%26c&j=k&d[e][f%26g]=h%2Ai'
    """
    def recursion(d, base=[]):
        pairs = []

        for key, value in d.items():
            new_base = base + [key]
            if hasattr(value, 'values'):
                pairs += recursion(value, new_base)
            else:
                new_pair = None
                if len(new_base) > 1:
                    first = urllib.quote(new_base.pop(0))
                    rest = map(lambda x: urllib.quote(x), new_base)
                    new_pair = "%s[%s]=%s" % (first, ']['.join(rest), urllib.quote(unicode(value)))
                else:
                    new_pair = "%s=%s" % (urllib.quote(unicode(key)), urllib.quote(unicode(value)))
                pairs.append(new_pair)
        return pairs

    return '&'.join(recursion(d))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

不过,我很想知道是否有更好的方法可以做到这一点.我不敢相信Python的标准库无法实现这一点.

Still, I'd be interested to know if there's a better way to do this. I can't believe Python's standard library doesn't implement this.

这篇关于在python中用urlencode多维字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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