Python字典操作

时间:2016-08-03 09:05:29

标签: python dictionary

我有类似下面的词典:

dict = {}
dict[(-1,"first")]=3
dict[(-1,"second")]=1
dict[(-1,"third")]=5
dict[(0,"first")]=4
dict[(0,"second")]=6
dict[(0,"third")]=7
dict[(1,"first")]=34
dict[(1,"second")]=45
dict[(1,"third")]=66
dict[(2,"first")]=3
dict[(2,"second")]=1
dict[(2,"third")]=2

我现在想要的是具有以下结构的词典: 钥匙是"第一" "第二" "第三个",值是数字 - >开始:如果第一次进入元组> 0

dict_1 ={"first": [4,34,3], "second": [6,45,1], "third": [7,66,2]}

我尝试过:

for key, value in dict.iteritems():
   if key[0] <=0:
..
..

但是这会改变顺序并且不能正常工作。 如果有人建议一个简单的方法来处理这些事情,那就太好了。

非常感谢

4 个答案:

答案 0 :(得分:2)

为什么要保留订单? 我建议你使用这种循环

dict_r = {}
dict_r["first"] = []
dict_r["second"] = []
dict_r["third"] = []
for i in range (0,3):
    dict_r["first"].append(dict[i,"first"])
    dict_r["second"].append(dict[i,"second"])
    dict_r["third"].append(dict[i,"third"])

<强>更新

如果您不知道dict中有多少项

dict_r = {}
dict_r["first"] = []
dict_r["second"] = []
dict_r["third"] = []


for key, value in dict.iteritems():
   if key[0] <=0:
       dict_r[key[1]].append(value)

答案 1 :(得分:1)

为方便起见,我会使用defaultdict做类似的事情:

from collections import defaultdict
new_dict = defaultdict(list)

for (x,k),v in sorted(old_dict.items()): # iterating over the sorted dictionary 
    if x >= 0:
        new_dict[k].append(v)

dict(new_dict)
#output:
{'second': [6, 45, 1], 'first': [4, 34, 3], 'third': [7, 66, 2]}

顺便说一句,不要为你的字典命名dict,它是影子python dict类型。

答案 2 :(得分:0)

dict = {}
dict[(-1,"first")]=3
dict[(-1,"second")]=1
dict[(-1,"third")]=5
dict[(0,"first")]=4
dict[(0,"second")]=6
dict[(0,"third")]=7
dict[(1,"first")]=34
dict[(1,"second")]=45
dict[(1,"third")]=66
dict[(2,"first")]=3
dict[(2,"second")]=1
dict[(2,"third")]=2

dict_1 = {}
for num,txt in sorted(dict.keys()):
    if num >= 0:
        val = dict[(num,txt)]
        if txt in dict_1:
            dict_1[txt].append(val)
        else:
            dict_1[txt] = [val]

print dict_1

答案 3 :(得分:0)

    t = {}
    t[(-1,"first")]=3
    t[(-1,"second")]=1
    t[(-1,"third")]=5
    t[(0,"first")]=4
    t[(0,"second")]=6
    t[(0,"third")]=7
    t[(1,"first")]=34
    t[(1,"second")]=45
    t[(1,"third")]=66
    t[(2,"first")]=3
    t[(2,"second")]=1
    t[(2,"third")]=2
    
    new = {}
    for k in sorted(t.keys()):
        if k[0]>-1:
            if k[1] not in new:
                new[k[1]] = []
            new[k[1]].append(t[k])

    from pprint import pprint
    pprint(new)
    # {'first': [4, 34, 3], 'second': [6, 45, 1], 'third': [7, 66, 2]}