简体   繁体   English

如何从字典打印?

[英]How can I print from a dictionary?

I am wondering how I can print all keys in a dictionary on one line and values on the next so they line up. 我想知道如何才能将字典中的所有键打印在一行上,而值又打印在下一行,以便它们对齐。

The task is to create a solitaire card game in python. 任务是用python创建纸牌纸牌游戏。 Made most of it already but I wish to improve on the visual. 已经完成了大部分操作,但是我希望在视觉效果上有所改善。 I know how to use a for loop to print lines for each value and key, but the task I'm doing in school asks me to do it this way. 我知道如何使用for循环为每个值和键打印行,但是我在学校正在做的任务要求我这样做。 I also just tried to create new lists for each line and "print(list1)" print(list2) but that just looks ugly. 我还尝试为每行和“ print(list1)” print(list2)创建新列表,但这看起来很丑。

    FireKort ={
        'A': None,#in my code i have the cards as objects here with value 
    #and type
        'B': None,#ex. object1: 8, cloves; object2: King, hearts 
        'C': None,
        'D': None,
        'E': None,
        'F': None,
        'G': None,
        'H': None
        }
    def f_printK():
        global FireKort
        for key in FireKort:
            print('Stokk:',key,' Gjenstående:',len(FireKort[key]))
            try:
                print(FireKort[key][0].sort, FireKort[key][0].valør)
            except:
                print('tom')


    ##here are the lists i tried:
    ##    navn=[]
    ##    kort=[]
    ##    antall=[]
    ##    for key in FireKort:
    ##        navn.append((key+' '))
    ##        kort.append([FireKort[key][0].sort,FireKort[key][0].valør])
    ##        antall.append(  str(len(FireKort[key])))
    ##    print(navn)
    ##    print(kort)
    ##    print(antall)

ABCDEFGH [♦9][♣A][♠Q][♣8][♦8][♣J][♣10][♦7] 4 4 4 4 4 4 4 4 ABCDEFGH [♦9] [♣A] [♠Q] [♣8] [♦8] [♣J] [♣10] [♦7] 4 4 4 4 4 4 4 4 4

Have you try to use pprint ? 您尝试使用pprint吗?

The pprint module provides a capability to “pretty-print arbitrary Python data structures pprint模块提供了“漂亮地​​打印任意Python数据结构的功能”。

https://docs.python.org/2/library/pprint.html https://docs.python.org/2/library/pprint.html

Try this: 尝试这个:

d = { ... }
keys = [ str(q) for q in d.keys() ]
values = [ str(q) for q in d.values() ]
txts = [ (str(a), str(b)) for a, b in zip(keys, values) ]
sizes = [ max(len(a), len(b)) for a, b in txts ]
formats = [ '%%%ds' % q for q in sizes ]
print(' '.join(a % b for a, b in zip (formats, keys)))
print(' '.join(a % b for a, b in zip (formats, values)))

In short: 简而言之:

  • first we get str values of keys and values of dictionary d (since we're going to use them twice, we might as well store them locally) 首先,我们获得键的str值和字典d的值(由于我们将使用它们两次,因此不妨将它们存储在本地)
  • we calculate max size of each "column" 我们计算每个“列”的最大大小
  • we create formats for % operator 我们为%运算符创建格式
  • and we print 然后我们打印

It could be done using ljust method of str . 可以使用str ljust方法来完成。 Example: 例:

d = {'A':'some','B':'words','C':'of','D':'different','E':'length'}
keys = list(d.keys())
values = list(d.values())
longest = max([len(i) for i in keys]+[len(i) for i in values])
print(*[i.ljust(longest) for i in keys])
print(*[i.ljust(longest) for i in values])

Output: 输出:

A         B         C         D         E        
some      words     of        different length   

Note that I harnessed fact that .keys() and .values() return key and values in same order, if no action was undertaken between them regarding given dict . 请注意,如果没有对给定dict进行任何操作,我会利用.keys().values()返回键和值的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 的 GUI 中打印字典中的所有值 - How can i print all values from a dictionary in a GUI in Python 如何在 tkinter 的列表框中打印字典列表 - How can i print a dictionary list in a listbox from tkinter 如何从这个 traccar output 字典中打印单个项目? - How can I print a single item from this traccar output dictionary? Python 中的 Discord ChatBot:如何从字典中打印某些内容? - Discord ChatBot in python: How can I print something from a dictionary? 如何在下面的代码中打印字典中的值? - How can I print a value from dictionary on the below code? 如何在Python中的字典中打印列表? - How can I print list in dictionary in Python? 如何以表格形式打印此词典? - How can i print this dictionary in form of a table? 如何从字典值中删除[]和'',以便可以在csv文件中正确打印 - How do I remove [ ] and ' ' from my dictionary values so that I can print it properly in a csv file 如何选择要从python字典中打印出的内容并将其写到另一个文件中? - How can I choose what to print out from a python dictionary and write it out to another file? Python-如何从列表中的许多词典中打印某个词典字段? - Python - How can i print a certain dictionary field from many dictionaries within a list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM