8

I have a dict containing files and their owners.

files = {
      'Input.txt': 'Randy',
      'Code.py': 'Stan',
      'Output.txt': 'Randy'
   }

How can I group the files with similar owners to get something like this

{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}.
James Njuguna
  • 604
  • 2
  • 12
  • 24

2 Answers2

11

You could retrieve the unique names first, then iterate through each name, grouping files under the name.

# store the names (the keys of the new dict) as a set (keeps elements unique)
names = set(files.values())

# use a list comprehension, iterating through keys and checking the values match each n
d = {}
for n in names:
    d[n] = [k for k in files.keys() if files[k] == n]

You could also opt for a dict-comprehension:

d = {n:[k for k in files.keys() if files[k] == n] for n in set(files.values())}

Result:

{'Stan': ['Code.py'], 'Randy': ['Input.txt', 'Output.txt']}
TrebledJ
  • 8,713
  • 7
  • 26
  • 48
-1

Iterate through the first dictionary, getting the keys and values.

For each value, check if it exists in a new, blank/empty dictionary. If not, add a key (of the original value), assigning a blank array to it.

Unconditionally add the corresponding original key to the array (in the second dictionary) for the original value (as a key in the second dictionary).

The following pseudocode should get you started

dict2 = {}
for (key, value in files):
  if value not in dict2:
    dict2[value] = []
  dict2[value].add(key)
print(repr(dict2))
Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38