How to get dictionary keys using a tuple, where dictionary keys are stored in list and values in tuple
Question:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
"""code here"""
For the above code I need to get the output as :
a
b
c
I know if we put print(i), we will get the desired output, but the answer expected is in terms of K.
Actual answer is: print(k[0]),which I am unable to understand.
Thanks
Answers:
Since you define values of dictionary
equal to a tuple here:
dictionary[my_list[i]] = (my_list[i],)
k is a tuple which means for it to print the actual value you need to get the first item in k by using the following:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
print(k[0])
Output:
a
b
c
k[0]
just gets the first item in the tuple ('a',)
. This makes it print a
instead of ('a',)
.
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
"""code here"""
For the above code I need to get the output as :
a
b
c
I know if we put print(i), we will get the desired output, but the answer expected is in terms of K.
Actual answer is: print(k[0]),which I am unable to understand.
Thanks
Since you define values of dictionary
equal to a tuple here:
dictionary[my_list[i]] = (my_list[i],)
k is a tuple which means for it to print the actual value you need to get the first item in k by using the following:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
print(k[0])
Output:
a
b
c
k[0]
just gets the first item in the tuple ('a',)
. This makes it print a
instead of ('a',)
.