如果已经存在相同的密钥,我在添加新值时遇到问题,我也无法创建新的对。
这是我的代码:
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'}
答案 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)