python字典类型实现的键值对的映射_遍历Python字典中的键值对来构建对象列表

1586010002-jmsa.png

6jWaf.png

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

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 ]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值