我有所有子目录subdirectories
的列表。
Oceans\
Pacific_123\
20140306\
20131217\
Atlantic_456\
20101203\
20160723\
20140306\
Indian_789\
20110509\
>>> print(subdirectories)`
['/Oceans/Pacific_123/20140306', '/Oceans/Pacific_123/20140306', '/Oceans/Atlantic_456/20101203', '/Oceans/Atlantic_456/20160723', '/Oceans/Atlantic_456/20140306', '/Oceans/Indian_789/20110509']
我正在创建一个字典marginal
,其中subdirectories
列表的海洋或Oceans
的1级是键,而值是ID或2级
我想要的marginal
应该看起来像这样:
>>> print(marginal)
{'123': ['20140306', '20131217'], '456': ['20101203', '20160723', '20140306'], '789': '20110509'}
我正在遍历subdirectories
以创建此字典。如果密钥在我的循环的先前迭代中存在,如何创建第二个值/附加第二个值?
>>> pairs = dict()
>>> for subdirectory in subdirectories:
... pairs.update({subdirectory:subdirectory[20:]})
答案 0 :(得分:1)
subdirectories = ['/Oceans/Pacific_123/20140306', '/Oceans/Pacific_123/20140306', '/Oceans/Atlantic_456/20101203', '/Oceans/Atlantic_456/20160723', '/Oceans/Atlantic_456/20140306', '/Oceans/Indian_789/20110509']
marginal = {}
for s in subdirectories:
prefix, delim, postfix = s.rpartition('/')
_, _, key = prefix.rpartition('_')
marginal.setdefault(key, []).append(postfix)
print(marginal)
结果
{'123': ['20140306', '20140306'], '456': ['20101203', '20160723', '20140306'], '789': ['20110509']}