如果在字典中找到相同的键,则将值附加为列表

时间:2017-07-27 18:29:44

标签: python dictionary

如果已经存在相同的密钥,我在添加新值时遇到问题,我也无法创建新的对。

这是我的代码:

some_dirs = [
'/hosts/serverA/data/material_metal',
'/hosts/serverB/data/material_paper',
'/hosts/serverA/data/general_material',
'/hosts/users/data/testing']

some_dict = {}
for dir in some_dirs:
    server_name = dir.split('/')[2]
    if server_name.startswith('server'):
        dir_name = dir.split('/')[-1]
        some_dict[server_name] = dir_name

我得到以下输出:

{'serverA': 'general_material', 'serverB': 'material_paper'}

我期待以下(2中的1个):

# Output 1
{'serverA': 'general_metal', 'serverB': 'material_paper', 'serverA': 'general_material'}
# Output 2
{'serverA': ['general_metal', 'general_material'], 'serverB': 'material_paper'}

1 个答案:

答案 0 :(得分:0)

some_dirs = [
'/hosts/serverA/data/material_metal',
'/hosts/serverB/data/material_paper',
'/hosts/serverA/data/general_material',
'/hosts/users/data/testing']
some_dict = {}
for dir in some_dirs:
    server_name = dir.split('/')[2]
    if server_name.startswith('server'):
        dir_name = dir.split('/')[-1]
        if server_name not in some_dict:
            some_dict[server_name] = [dir_name]
        else:
            some_dict[server_name].append(dir_name)