Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isnt the output showing k1, k2, k3?

Tags:

python

I've been trying to learn Python and have come across this issue. I can't figure out how the current output came about.

d={'k1':1,'k2':2,'k3':3}
for key,value in d.keys() :
    print(key)

Output:

k
k
k

I expected the output to be:

k1
k2
k3
like image 796
heisenberg_0120 Avatar asked Jul 27 '19 13:07

heisenberg_0120


1 Answers

You are trying to print all key, value pair from your dictionary d. But you are only able to see first character of the key when you try to print key. I will explain you by splitting your for loop for key,value in d.keys().

This is your dictionary, d

d = {'k1':1,'k2':2,'k3':3}

The for loop takes d.keys() and iterates. d.keys() look like this

print(d.keys()) # outputs dict_keys(['k1', 'k2', 'k3'])

for loop iterates over this list of keys ['k1', 'k2', 'k3']

But when you do, this

key,value = 'k1' # this happens with each of the keys in the list 
print(key,value) # output k 1

Your key k1 got split into two single character strings k and 1 which can be termed as an unintentional tuple creation @inquisitiveOne and gets assigned to key and value variables respectively.

When you try to print value inside the for loop, you will see 1, 2, 3 but that is in fact the second character of the key attribute and not the value attribute. If you try printing, print(type(value)) you will get to know that it is in fact a string variable and not an integer.


To get the proper value of the key you need to only use a single variable.

d={'k1':1,'k2':2,'k3':3}
for key in d.keys():
    print(key)

Output:

k1
k2
k3

As mentioned by @asikorski you can achieve the same using just for key in d: print(key)


If you need to get key, value pairs. Then use d.items()

for key,value in d.items():
    print(key,value)

Output:

k1 1
k2 2
k3 3

Hope it helps!

like image 120
CodeIt Avatar answered Oct 13 '22 10:10

CodeIt