1

I have a requirement where I have to basically reverse keys and values in a dictionary.

If the key is already present, it should append the new element value to the existing one.

I wrote a code for this. It is working fine. But if I re-assign the dictionary item instead of appending it, with a new element, instead of overwriting, it is creating None in place of value.

Here is the working code:

def group_by_owners(files):
    dt = {}
    for i,j in files.items():
        if j in dt.keys():
            dt[j].append(i) # Just appending the element
        else:
            dt[j]=[i]
    return dt

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}   
print(group_by_owners(files))

Correct Output: {'Stan': ['Code.py'], 'Randy': ['Input.txt', 'Output.txt']}

Here is the code that is giving wrong output:

def group_by_owners(files):
    dt = {}
    for i,j in files.items():
        if j in dt.keys():
            dt[j] = dt[j].append(i) # Re-assigning the element. This is where the issue is present.
        else:
            dt[j]=[i]
    return dt

files = {
    'Input.txt': 'Randy',
    'Code.py': 'Stan',
    'Output.txt': 'Randy'
}   
print(group_by_owners(files))

Incorrect Output: {'Stan': ['Code.py'], 'Randy': None}

I'm not sure if there will be any difference between re-assigning the dictionary element value and appending the existing value.

Someone, please clarify.

Underoos
  • 4,708
  • 8
  • 42
  • 85

1 Answers1

1

Replace your for loop:

for i,j in files.items():
        if j in dt.keys():
            dt[j] = dt[j].append(i) # Re-assigning the element. This is where the issue is present.
        else:
            dt[j]=[i]

TO

for key, value in files.items():
    # if dictionary has same key append value
    if value in list(dt.keys()):
        dt[value].append(key)
    else:
        dt[value] = [key]

OR

Add an item to the end of the list. Equivalent to a[len(a):] = [x]

for key, value in files.items():
    if value in list(dt.keys()):
        dt[value][len(dt[value]):] = [key]
    else:
        dt[value] = [key]

O/P:

{'Randy': ['Input.txt', 'Output.txt'], 'Stan': ['Code.py']}

More details list append method

bharatk
  • 4,202
  • 5
  • 16
  • 30