Merging lists and dicts in Python with fromkeys() method

605 Views Asked by At

I am very new in Python and I am confused in using .formkeys() method with lists.

Here's my code below:

    # dictionary exercise 4: Initialize dictionary with default values
employees = ['Kelly', 'Emma', 'John']
defaults = {"designation": 'Application Developer', "salary": 8000}

def_dictionary = dict()
def_dictionary.setdefault("designation", "Application Developer")
def_dictionary.setdefault("salary", 8000)
print(def_dictionary)

res_dict = dict.fromkeys(employees[0], defaults)

print(res_dict)

    print(res_dict)

Here, the output is

{'K': {'designation': 'Application Developer', 'salary': 8000}, 'e': {'designation': 'Application Developer', 'salary': 8000}, 'l': {'designation': 'Application Developer', 'salary': 8000}, 'y': {'designation': 'Application Developer', 'salary': 8000}}

What I want to do is pair employee "Kelly" with the default values dictionary, however, I don't understand why I get 'K', 'E', 'L', 'Y' strings as keys to my res_dict.

I know the solution should be

res_dict = dict.fromkeys(employees, defaults)

I am just wondering why the code parses Kelly to 'K', 'E', 'L', 'Y'.

Thank you

2

There are 2 best solutions below

0
DanielB On

employees[0] is the str "Kelly". str objects are iterable - it will give you each character in sequence, E.g.

for c in "Kelly":
    print(c)

Produces:

K
e
l
l
y

So, when you call dict.fromkeys("Kelly", None) you get a key for each character in "Kelly".

0
akash mohan On

Sine dict.fromkeys(employees,defaults) iterate for every element in employees,employees[0] will pass the 0th index of every iterable as a key.

employees = ['Kelly', 'Emma', 'John']
defaults = {"designation": 'Application Developer', "salary": 8000}
d = {}
key = [employees[0]]
d = d.fromkeys(key,defaults)
print(d)

will give you the answer the you required.