Python:附加到dict值,如果已经存在则是一个列表,而不是添加所有键的值

时间:2016-10-25 15:19:39

标签: python list python-3.x dictionary

根据示例代码,Python输出未正确地将字符串值添加到循环内的dict键的列表值。

收到的输出:

{'one': ['dev-1', 'dev-3'], 'three': ['dev-1', 'dev-3'], 'five': ['dev-3'],
    'four': ['dev-3'], 'two': ['dev-1', 'dev-3']}

预期产出:

{'one': ['dev-1', 'dev-3'], 'three': ['dev-1'], 'five': ['dev-3'], 
    'four': ['dev-3'], 'two': ['dev-1']}

这是代码:

grp = ['instance "dev-1"\n', 'row id 68\n', 'grp mem "one"  "two" "three"\n', 'next\n',
    'instance "dev-3"\n', 'row id 18d\n', 'grp mem "four" "five" "one"', 'next\n']
grp_no = 0
mapping_dict = {}
current_grp = []
while grp_no < len(grp):
    line = grp[grp_no]
    if grp_no < len(grp):
        instance = line.startswith('instance ')
        grp_member = line.startswith('grp mem ')
        if not (instance or grp_member):
            grp_no += 1
            continue
        if instance:
            obj_id = (line.split()[1]).strip('"')
            current_grp.append(obj_id)
        if grp_member:
            current_members = line.split()
            for i in range(2, len(current_members), 1):
                mem = current_members[i]
                mem = mem.strip('"')
                check_point = mem in mapping_dict and (obj_id in mapping_dict[mem])
                check_point1 = mem in mapping_dict and not obj_id in mapping_dict[mem]
                if check_point:
                    continue
                elif check_point1:
                    (mapping_dict[mem]).append(obj_id)
                else:
                    mapping_dict[mem] = current_grp
            current_grp = []
    grp_no += 1
print(mapping_dict)

1 个答案:

答案 0 :(得分:1)

您的问题是您在多个词典键之间共享相同的列表:

>>> for k, v in mapping_dict.items():
...     print(id(v), k, v)
...
41955656 four ['dev-3']
41897936 one ['dev-1', 'dev-3']
41897936 three ['dev-1', 'dev-3']
41897936 two ['dev-1', 'dev-3']
41955656 five ['dev-3']

有一种更容易实现目标的方法:

mapping_dict = {}
instance = None
for line in grp:
    if line.startswith('instance'):
        instance = line.split('"')[1]
    elif line.startswith('grp mem'):
        for member in line[7:].replace('"', '').split():
            mapping_dict.setdefault(member, []).append(instance)