Search code examples
pythondictionary-comprehension

Why my dictionary comprehension only change the first key/value


I'm new to python and I wonder why this simple code does not return all the 3 keys/values of my dictionary ? I am trying to create a dictionary and then reverse it .

employees = ['Kelly', 'Emma', 'John']

myNewDict1=dict.fromkeys(employees,"Hi")

newDict2 = { ky: vl for vl, ky in myNewDict1.items() } 

print(newDict2.items())

Here is what I see as result in my terminal :

dict_items([('Hi', 'John')])

While I expect to see all the three keys/values reversed .


Solution

  • Try this approach, using a dictionary it's not possible but you can use a tuple..

    employees = ['Kelly', 'Emma', 'John']
    print([('Hi', emp) for emp in employees])
    

    Or One liner,

    print(list(map(lambda x: ('Hi',x), ['Kelly', 'Emma', 'John'])))
    

    Output:

    [('Hi', 'Kelly'), ('Hi', 'Emma'), ('Hi', 'John')]