Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (12.7k points)

I'm totally new to python and totally confused with .formkeys() with lists.

Look at my code:

    # 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)

Output:

{'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 need to do is pair worker "Kelly" with the default esteems dictionary, notwithstanding, I don't comprehend why I get 'K', 'E', 'L', 'Y' strings as keys to my res_dict.

res_dict = dict.fromkeys(employees, defaults)

I don't know why my code gives kelly to 'K','E','L','Y'.

Thank you

1 Answer

0 votes
by (26.4k points)

Here, employee[0] is a string, "kelly"

str objects are iterable - it will give you each character in sequence

For example:

for c in "kelly":

     print(c)

Which produces:

k

e

l

l

y

You will get a key for an each character in "kelly", when you call the function dict.fromkeys("Kelly",None)

Join the python online course fast, to learn python concepts in detail and get certified.

Browse Categories

...