Python Printing Dictionary Key and Value side by side

可紊 提交于 2019-12-13 09:59:10

问题


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 the a program that prints in the following form:

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

回答1:


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

for key in d.keys():
    for value in d[key]:
        print key,value

edit:

A more elegant solution may be:

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



回答2:


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/




回答3:


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



回答4:


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

for x in d:
    for y in d[x]:
        print(x+",",y)

Output

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


来源:https://stackoverflow.com/questions/47207495/python-printing-dictionary-key-and-value-side-by-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!