florence-y
florence-y

Reputation: 871

Append to value in dict if key exists / convert value to list then append

I have a list of all subdirectories, 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']

I am creating a dictionary, marginal, where the oceans of the subdirectories list, or level 1 of Oceans, are keys, and the values are the IDs, or level 2.

My desired marginal should look something like this:

>>> print(marginal)
{'123': ['20140306', '20131217'], '456': ['20101203', '20160723', '20140306'], '789': '20110509'}

I am iterating over subdirectories to create this dictionary. How do I create a second value/append it if the key exists from a previous iteration of my loop?

>>> pairs = dict()
>>> for subdirectory in subdirectories:
    ...     pairs.update({subdirectory:subdirectory[20:]})

Upvotes: 1

Views: 373

Answers (1)

DarrylG
DarrylG

Reputation: 17156

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)

Result

{'123': ['20140306', '20140306'], '456': ['20101203', '20160723', '20140306'], '789': ['20110509']}

Upvotes: 1

Related Questions