aiohttp php类似帖子中的数组

时间:2019-07-17 11:59:31

标签: python post http-post aiohttp

我收到了数组:

MultiDict({'data[0]': 'test', 'data[1]': 'test', 'data[2]': 'test', 'hash': 'b5a1f45733f0949ed80f1ef4eaef5454667e4eeb0b77233e15a796e6c91c088b'})

我需要像php的排序数组那样迭代数据:

foreach ($_POST["data"] as $entry) {
    $hash .= $entry;
}

在php hash == 'testtesttest'

尝试

>>> keys = list(filter( lambda x: x.split('[')[0] == 'data', post.keys()))
>>> list(keys)
['data[0]', 'data[1]', 'data[2]']
>>> for x in keys:
...    print(int( x.split('[')[1].split(']')[0] ))
... 
0
1
2
>>> sorted(keys, key = lambda x : int( x.split('[')[1].split(']')[0] ))
['data[0]', 'data[1]', 'data[2]']
>>> for k in keys:
...     hash += post[k]

1 个答案:

答案 0 :(得分:1)

具有排序键和str.startswith功能:

# sample dict
d = {'data[2]': 'test2', 'data[1]': 'test1', 'data[10]': 'test10',
     'data[0]': 'test0', 'hash': 'b5a1f45733f0949ed80f1ef4eaef5454667e4eeb0b77233e15a796e6c91c088b'}

data = ''.join(d[k] for k in sorted((k_ for k_ in d.keys() if k_.startswith('data[')),
                                    key=lambda x: int(x.strip('data[]'))))
print(data)

输出:

test0test1test2test10