【问题标题】:How to take output of this function and use it as a dictionary?如何获取此函数的输出并将其用作字典?
【发布时间】:2019-08-07 10:57:40
【问题描述】:

代码

data = 'address'
print(data.id)

当我运行此代码时,它将打印以下输出

(('instance', u'id 123456789'),)

如何把这个输出变成这样的字典

{"id":"123456789"} 

【问题讨论】:

  • 如何 print dataa.id 给出输出?数据不是字典!您需要显示您的数据对象
  • 我要求将此(('instance', u'id 123456789'),) 转换为字典

标签: python python-3.x loops dictionary


【解决方案1】:
d = dict([data.id[0][1].split()])

其中data.id 是:在本例中为(('instance', u'id 123456789'),)

【讨论】:

    【解决方案2】:

    你可以做类似...

    res={} #initialize dictionary
    res['id']=id(data)
    print(res) 
    

    结果:

    {'id': 1754862887072}

    除此之外……

    print(data.id)  # will throw error, str does not have id property
    

    【讨论】:

      【解决方案3】:

      试试这个

      k, v = (('instance', u'id 123456789'),)[0][1].split()
      d = {str(k) : str(v)}
      print(d)
      

      我应该输出这个

      {'id': '123456789'}
      

      要将它们作为 unoce 字符串取出 str(..)。 (在 python 3.x 中,unicode 与 str 相同

      【讨论】:

      • 这不会返回字典
      【解决方案4】:
      >>> out = (('instance', u'id 123456789'),)
      >>> a,b = list(out).pop()
      >>> dict([str(b).split()])
      {'id': '123456789'}
      

      【讨论】:

        猜你喜欢
        • 2021-08-17
        • 1970-01-01
        • 2018-10-03
        • 1970-01-01
        • 1970-01-01
        • 2011-05-15
        • 2019-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多