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.