1

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

Burakhan Aksoy
  • 319
  • 3
  • 14
  • 2
    Note that `defaults` in your sample is a mutable value (a `dict`), so when you use it the `value` option in `dict.fromkeys`, each entry will have the same value. Later, when you modify a value it will be changed for *all instances*. Instead, you should use something like `dict.fromkeys(employees, defaults.copy())`. – DanielB May 24 '20 at 08:11
  • Note that you may want to do a basic Python tutorial that introduces the core data types and how to work with them. For example, ``def_dictionary.setdefault`` either doesn't do what you think it does, or it should not be used for what you want it to do. To store a key value pair, use ``def_dictionary["designation"] = "Application Developer"`` - or store it when creating the dict using a ``{key: value, ...}`` literal. Also, when having multiple objects with the same kind of data, consider using a ``class`` - in specific a ``dataclass`` or ``NamedTuple``. – MisterMiyagi May 24 '20 at 08:14

2 Answers2

2

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".

DanielB
  • 2,798
  • 1
  • 19
  • 29
1

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.