如果键存在,则追加到dict中的值/将值转换为列表,然后追加

时间:2019-11-13 21:10:53

标签: python list dictionary for-loop key-value

我有所有子目录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:]})

1 个答案:

答案 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']}