根据某些条件

时间:2017-10-31 10:43:46

标签: python dictionary

我有下表

table = {}
table["A"] = {0: {"B":2, "C1":2},   1: {"C1":1}}
table["B"] = {0: {"C":1},           1: {"C2":1}}
table["C"] = {0: {"C1":1},          1: {"C2":1}}

并希望将以下值添加到相应的键

c1 = {0:{"B":1}}    #This is for row "A"
c2 = {1:{"C":1}}    #This is for row "B"
c3 = {1:{"C2":1}}   #This is for row "C"

我想在表中插入c1,c2和c3,以便对于A,将对照0或1检查密钥。如果表中存在密钥,我需要查看值并检查对于键值1内的B,如果存在B,我需要增加该值。否则,{“B”:1}将被添加到0或1(基于密钥)

我尝试了许多技术,但总是以错误消息结束,或者相应的值未更新。

结果表应为

 table["A"] = {0: {"B":**3**, "C1":2},   1: {"C1":1}}
 table["B"] = {0: {"C":1},           1: {"C2":1}, **{"C":1}**}
 table["C"] = {0: {"C1":1},          1: {"C2":**2**}}

更新: 虽然@RomanPerekhrest提供的解决方案有效,但是当我尝试进行这些更改时,我收到错误消息。

## to create the c1, c2, c3 etc from the list, I added this code. 
tr = ["A",0,"B",1,"C",1,"C2",1]
transition = {}
for i in range(1,len(tr)-2,2):
    transition[i] = {tr[i]:{tr[i+1]:1}}
## instead of the c1, c2 and c3 i want to use the transition
##c1 = {1:{"B":1}}
##c2 = {1:{"C":1}}
##c3 = {1:{"C2":1}}

##for k,d in zip(table.keys(), [c1,c2,c3]): this is working correctly. 

for k,d in zip(table.keys(), transition): ##the transition is generating error message for c_k,c_v in d.items():AttributeError: 'int' object has no attribute 'items'
     for c_k,c_v in d.items():
         if c_k in table[k]:
             for inner_k in c_v:
                 if table[k][c_k].get(inner_k):
                    table[k][c_k][inner_k] += c_v[inner_k]
                 else:
                     table[k][c_k][inner_k] = c_v[inner_k]
 print(table)

2 个答案:

答案 0 :(得分:1)

直截了当地说:

table = {}
table["A"] = {0: {"B":2, "C1":2}, 1: {"C1":1}}
table["B"] = {0: {"C":1}, 1: {"C2":1}}
table["C"] = {0: {"C1":1}, 1: {"C2":1}}

c1 = {0:{"B":1}}
c2 = {1:{"C":1}}
c3 = {1:{"C2":1}}

for k,d in zip(table.keys(), [c1,c2,c3]):
    for c_k,c_v in d.items():
        if c_k in table[k]:
            for inner_k in c_v:
                if table[k][c_k].get(inner_k):
                    table[k][c_k][inner_k] += c_v[inner_k]
                else:
                    table[k][c_k][inner_k] = c_v[inner_k]

print(table)

输出:

{'A': {0: {'B': 3, 'C1': 2}, 1: {'C1': 1}}, 'B': {0: {'C': 1}, 1: {'C2': 1, 'C': 1}}, 'C': {0: {'C1': 1}, 1: {'C2': 2}}}

答案 1 :(得分:0)

尝试:

from collections import Counter

table = {
         'A': {0: Counter(['B', 'C1'] * 2), 1: Counter(['C1'])},
         'B': {0: Counter(['C'      ]    ), 1: Counter(['C2'])},
         'C': {0: Counter(['C1'     ]    ), 1: Counter(['C2'])},
        }

modifications = {
                 'A': {0: Counter(['B' ])},
                 'B': {1: Counter(['C' ])},
                 'C': {1: Counter(['C2'])},
                }

for key_m, value_m in modifications.items():
    for key, value in table[key_m].items():
        value.update(value_m.get(key, []))

print(table)

它使用collections.Counter,但它们作为大多数部分的序列,除了他们的collections.Counter.update()方法增加了值而不是替换它。如果您想将名为collections.Counter的{​​{1}}转换为名为a的{​​{1}}使用dict