如何以不同的方式阅读字典?

时间:2016-07-21 12:30:35

标签: python list dictionary

我有一个词典,其中键是数字,值是一个或多个列表。我想读这本字典,以便我可以分开键和值。

字典 -

{
 1468332424064000: '[80000,2]',
 1468332423282000: '[30000,6]',
 1468332421081000: '[40000,2]',
 1468332424121000: '[30000,2][40000,2]',
 1468332424014000: '[60000,2]',
 1468332421131000: '[40000,2][30000,6]',
 1468332422921000: '[60000,2]',
 1468332421046000: '[40000,2]',
 1468332422217000: '[40000,2]',
 1468332424921000: '[40000,2]',
 1468332421459000: '[30000,6]',
 1468332422579000: '[60000,2][30000,6]',
 1468332422779000: '[30000,2]',
 1468332424161000: '[70000,6]'
}

程序编码 -

for k,v in latency_obj.d.iteritems():
     li = v.split()
     for l in li:
         print l

输出 -

[80000,2]
[30000,6]
[40000,2]
[30000,2][40000,2]
[60000,2]
[40000,2][30000,6]
[60000,2]
[40000,2]
[40000,2]
[40000,2]
[30000,6]
[60000,2][30000,6]
[30000,2]
[70000,6]

但我想将这两个列表作为单独的列表,以便我可以检索该列表的值。我有什么想法?

3 个答案:

答案 0 :(得分:0)

假设您希望结果看起来像

[80000,2]
[30000,2]
[40000,2]
[60000,2]
[30000,6]
[40000,2]
[30000,6]
[30000,2]
[40000,2]
[40000,2]
[70000,6]
[60000,2]
[30000,6]
[60000,2]
[40000,2]
[40000,2]
[30000,6]

我建议在[上拆分每个值,如下所示:

for k, v in d.iteritems():
    li = v.split('[')
    for l in li:
        if l:
            print '[' + l

答案 1 :(得分:0)

试试这个,

for key,value in d.items():
    d[key] = eval(value.replace(']','],',1))

<强>输出

{1468332421046000: ([40000, 2],),
 1468332421081000: ([40000, 2],),
 1468332421131000: ([40000, 2], [30000, 6]),
 1468332421459000: ([30000, 6],),
 1468332422217000: ([40000, 2],),
 1468332422579000: ([60000, 2], [30000, 6]),
 1468332422779000: ([30000, 2],),
 1468332422921000: ([60000, 2],),
 1468332423282000: ([30000, 6],),
 1468332424014000: ([60000, 2],),
 1468332424064000: ([80000, 2],),
 1468332424121000: ([30000, 2], [40000, 2]),
 1468332424161000: ([70000, 6],),
 1468332424921000: ([40000, 2],)}

因此,您可以将字符串更改为元组,并且可以访问所有值。

您可以像这样访问这些值。

In [1]: d[1468332421131000]
Out[1]: ([40000, 2], [30000, 6])
In [2]: d[1468332421131000][0]
Out[2]: [40000, 2]
In [3]: d[1468332421131000][1]
Out[3]: [30000, 6]
In [4]: d[1468332421131000][0][1]
Out[4]: 2

概念:

replace(']','],',1)会将]的第一次出现替换为],,并仅使用eval进行评估。并存储了相同的字典本身。

答案 2 :(得分:0)

考虑&#39;列表&#39;即,这里作为字符串讨论的字典值,可以使用正则表达式提取数字。

>>> import re
>>> lists = '[30000,2][40000,2]'
>>> out_list = re.findall('\d+',lists)
['30000', '2', '40000', '2']  # The elements are actually strings
>>> [eval(n) for n in out_list]
[30000, 2, 40000, 2]  # List containing numbers

希望这是你所期待的。