将字典的值从列表更改为标量值

时间:2016-10-28 06:56:48

标签: python list dictionary

我有一个Python字典(实际上是字典字典),其值是单个元素的列表。有没有快速的方法将相应的列表更改为标量值?

mydata = {0: {u'AM019J4O': [u'XAIXMZ2H'],
              u'BPJZMDRJ': [u'EKDZTAZJ'],
              u'CMNH1UAS': [u'EP8S0STW']},
          1: {u'AM019J4O': [u'X47VO9R8'],
              u'BPJZMDRJ': [u'EK5GPG4R'],
              u'CMNH1UAS': [u'RNANJHMK']}}

我想要的是

mydata = {0: {u'AM019J4O': u'XAIXMZ2H',
              u'BPJZMDRJ': u'EKDZTAZJ',
              u'CMNH1UAS': u'EP8S0STW'},
          1: {u'AM019J4O': u'X47VO9R8',
              u'BPJZMDRJ': u'EK5GPG4R',
              u'CMNH1UAS': u'RNANJHMK'}}

3 个答案:

答案 0 :(得分:0)

试试这个,

for k,v in mydata.items():
    mydata[k] = {k1: v1[0] for k1, v1 in v.items()}

它是一个嵌套的dict,因此迭代它并从列表中提取单个元素。

<强>工作

In [2]: for k,v in mydata.items():
   ...:         mydata[k] = {k1: v1[0] for k1, v1 in v.items()}
   ...:     

In [3]: mydata
Out[3]: 
{0: {u'AM019J4O': u'XAIXMZ2H',
  u'BPJZMDRJ': u'EKDZTAZJ',
  u'CMNH1UAS': u'EP8S0STW'},
 1: {u'AM019J4O': u'X47VO9R8',
  u'BPJZMDRJ': u'EK5GPG4R',
  u'CMNH1UAS': u'RNANJHMK'}}

答案 1 :(得分:0)

您必须遍历所有嵌套字典并从列表中提取单个元素:

mydata = {k: {nk: nv[0] for nk, nv in v.items()} for k, v in mydata.items()}

演示:

>>> {k: {nk: nv[0] for nk, nv in v.items()} for k, v in mydata.items()}
{0: {u'CMNH1UAS': u'EP8S0STW', u'AM019J4O': u'XAIXMZ2H', u'BPJZMDRJ': u'EKDZTAZJ'}, 1: {u'CMNH1UAS': u'RNANJHMK', u'AM019J4O': u'X47VO9R8', u'BPJZMDRJ': u'EK5GPG4R'}}
>>> pprint(_)
{0: {u'AM019J4O': u'XAIXMZ2H',
     u'BPJZMDRJ': u'EKDZTAZJ',
     u'CMNH1UAS': u'EP8S0STW'},
 1: {u'AM019J4O': u'X47VO9R8',
     u'BPJZMDRJ': u'EK5GPG4R',
     u'CMNH1UAS': u'RNANJHMK'}}

答案 2 :(得分:0)

import pprint
mydata = {0: {u'AM019J4O': [u'XAIXMZ2H'],
      u'BPJZMDRJ': [u'EKDZTAZJ'],
      u'CMNH1UAS': [u'EP8S0STW'],},
     1: {u'AM019J4O': [u'X47VO9R8'],
      u'BPJZMDRJ': [u'EK5GPG4R'],
      u'CMNH1UAS': [u'RNANJHMK'],}}


pprint.pprint(mydata)

def change(mydata):
    res = dict()
    for key, value in mydata.items():
        res[key] = {key: v[0] for key, v in value.items()}
    return res

pprint.pprint(change(mydata))

输出:

{0: {u'AM019J4O': u'XAIXMZ2H',
     u'BPJZMDRJ': u'EKDZTAZJ',
     u'CMNH1UAS': u'EP8S0STW'},
 1: {u'AM019J4O': u'X47VO9R8',
     u'BPJZMDRJ': u'EK5GPG4R',
     u'CMNH1UAS': u'RNANJHMK'}}