遍历Python字典中的键值对来构建对象列表 [英] Iterating through key value pairs in a python dictionary to build an list of objects
问题描述
在这种情况下,只有1个对象,但我怎样才能遍历json变量来构建我需要的dics列表?
我正在寻找一种方法来使代码容错多一点,能够处理单个和多个对象
简单的方法是检查进入的数据类型并更改它转换成其余代码可以使用的标准格式。如果你得到 dict
,只要创建一个 list
来存放 dict
json = request.get_json(force = True)#接收邮递员的请求j $ j
$ {'a':j ['key1'],'token':j ['key2']} for j in json]
I need to post some objects to a flask app where, with each object made of 2 key-value pairs.
I'm using postman to test sending 1 object as json, but I need the ability to send multiple objects ( again each of which are made of 2 kv pairs as in screenshot )
My flask app looks like:
json = request.get_json(force=True) # receives request from postman
for j in json:
print str(j)
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]
I would like rebuild the json into a list ('test') of dictionaries with dic containing 2 kv pairs (i.e. each dic is an object).
Unfortunately I realized that because json above is
{u'key2': u'xyz', u'key1': u'abc'}
I'm getting:
TypeError: string indices must be integers
please see TypeError: string indices must be integers with flask json
In this case there is only 1 object, but How can I iterate through the json variable to build the list of dics I need?
I was just looking for a way to make the code a little more fault tolerant and able to handle both single and multiple objects
The easy way to do that is to check the type of data coming in and change it into a standardized form that the rest of your code can consume. If you get a dict
just create a list
to hold the dict
and the rest of the code will work.
json = request.get_json(force=True) # receives request from postman
for j in json:
print str(j)
if isinstance(json, dict):
json = [json]
test = [{'a': j['key1'], 'token':j['key2']} for j in json ]
这篇关于遍历Python字典中的键值对来构建对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!