Skip to content Skip to sidebar Skip to footer

Python Printing Dictionary Key And Value Side By Side

I want a program that prints Key and Value side by side for the following code: This is a Dictionary: d = {'M': ['Name1', 'Name2', 'Name3'], 'F': ['Name1','Name2','Name3']} I want

Solution 1:

d = {'M': ['Name1', 'Name2', 'Name3'], 'F': ['Name1','Name2','Name3']} 

forkeyin d.keys():
    forvaluein d[key]:
        print key,value

edit:

A more elegant solution may be:

forkey,value in d.iteritems():
    print key,value

Solution 2:

You can try this:

d = {'M': ['Name1', 'Name2', 'Name3'], 'F': ['Name1','Name2','Name3']}
for a, b in d.items():
   for i in b:
       print("{}, {}".format(a, i))

Output:

M, Name1
M, Name2
M, Name3
F, Name1
F, Name2
F, Name3

Solution 3:

You can iterate on dict key, values.

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

I'd use this code as work since it is very clead about what is does.

If you want to skill up using itertools:

form itertools import product
 for key, value in d.items():
     for (k, v) in product([key], value):
        print k,v

You may also play with cycle and zip function or zip_longest function using the key as a fillvalue.

https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions your could also check this and use print in the list comprehension.

Other links: https://spapas.github.io/2016/04/27/python-nested-list-comprehensions/https://lerner.co.il/2015/07/23/understanding-nested-list-comprehensions-in-python/

Solution 4:

d = {'M': ['Name1', 'Name2', 'Name3'], 'F': ['Name1','Name2','Name3']}

forxin d:
    foryin d[x]:
        print(x+",",y)

Output

M, Name1
M, Name2
M, Name3
F, Name1
F, Name2
F, Name3

Post a Comment for "Python Printing Dictionary Key And Value Side By Side"