Reputation: 1
i need to access first element of nested lists and print it and also need to access second elements of every list and print it
details = {"name":["suresh","ramesh"],"age":[25,26],"city":["hyd","chn"]}
# print(" my name is {}, and age is {} and coming from {}".format())
# my name is suresh, age is 25 and coming from hyd
# my name is ramesh, age is 26 and coming from chn
unable to write
Upvotes: 0
Views: 54
Reputation: 1669
I took the Reference from Andrej's answer and here is modified code
details = {"name":["suresh","ramesh"],"age":[25,26],"city":["hyd","chn"]}
s = "my name is {}, and age is {} and coming from {}"
print(*map(lambda detail: s.format(*detail) , zip(*details.values())) , sep ='\n' )
This returns the expected output
my name is suresh, and age is 25 and coming from hyd
my name is ramesh, and age is 26 and coming from chn
Upvotes: 0
Reputation: 195613
You can use zip()
method with dict.values()
:
details = {"name":["suresh","ramesh"],"age":[25,26],"city":["hyd","chn"]}
s = "my name is {}, and age is {} and coming from {}"
for detail in zip(*details.values()):
print(s.format(*detail))
Prints:
my name is suresh, and age is 25 and coming from hyd
my name is ramesh, and age is 26 and coming from chn
EDIT: It's better to see what each step is doing:
dict.values()
holds:
dict_values([['suresh', 'ramesh'], [25, 26], ['hyd', 'chn']])
[*zip(*details.values())]
holds:
[('suresh', 25, 'hyd'), ('ramesh', 26, 'chn')]
Upvotes: 3