将值绑定到字典中的键然后打印

时间:2016-07-12 12:33:26

标签: python dictionary printing storing-data

这是我编写的主要代码的一小部分。根据用户选择,他们可以添加玩家信息,然后打印字典播放器名单中的信息。我想存储信息,然后以这种格式打印,但我还没有弄清楚如何做到这一点。                     名称 ****                     电话号码 ****                     泽西号**** 我是字典的新手,但我花了几个小时阅读和搜索过去几天关于词典的内容,并尝试了几种不同的方法来做到这一点但却失败了。我已经得到了最接近我现在设置的方式,但它仍然无法正常工作。我觉得我正在将信息错误地存储到字典中作为初学者,我们将非常感谢任何帮助。

player_roster = {}
def display_roster(self):                         #Print Roster
    if len(player_roster) != 0:
        for x in player_roster.keys():
            print('Name:', x, 'Phone Number:', player_roster[x])
    else:                                          #Print No One on Roster
        len(player_roster) == []
        print('No names have been entered:')

def add_player(self,):                              #Enter Members Name
    name = input('Enter New Players Name:')
    phone_number = input('Enter Players Phone Number:')
    jersey_number = int(input('Enter Players Jersey Number'))
    player_roster[name] = phone_number, 'Jersey Number', jersey_number
#If I input Toby as Name 444-444 as Phone Number and 3 as Jersey number it outputs like this
Name: Toby Phone Number: ('444-4444', 'Jersey Number', 3)
# I would like it to output like 
                                 Name: Toby
                                 Phone Number: 444-4444
                                 Jersey Number: 3

3 个答案:

答案 0 :(得分:1)

我会在代码中更改一些内容但要保持接近您要求的内容,请看一下:

def display_roster():
    if len(player_roster) != 0:
        for x in player_roster.keys():
            print('Name:', x)
            print('Phone Number:', player_roster[x][0])
            print('Jersey Number:', player_roster[x][1])
    else:
        print('Roster is empty.')
    return


player_roster = {}
def add_player():
    name = input('Enter New Players Name:\t')
    phone_number = input('Enter Players Phone Number:\t')
    jersey_number = int(input('Enter Players Jersey Number:\t'))
    player_roster[name] = [phone_number, jersey_number]
    return

add_player()
display_roster()

# PRINTS:
#Name: Toby
#Phone Number: 444-4444
#Jersey Number: 3

以多行打印可为您提供所需的结果。正如评论中所述,这也可以使用单个print()语句完成,但我认为紧凑代码对您没有太大影响。

此外,这条len(self.player_roster) == []行没有意义。这就像在一行中简单地写True一样好。 "空虚"该团队的成员由else:检查。

最后,我会略微改变玩家存放在"花名册"字典并像这样:{"Toby": ['444-4444', 3], ...}

答案 1 :(得分:0)

你几乎就在那里。以下修改将允许您根据需要进行打印(并且稍微更具可读性):

class PlayerDictionary():
    def __init__(self):
        pass
    player_roster = {}
    def display_roster(self):                         #Print Roster
        if len(self.player_roster) != 0:
            for key, value in self.player_roster.iteritems():
                print(str(key) + ": " + str(value))
        else:                                          #Print No One on Roster
            len(self.player_roster) == []
            print('No names have been entered:')

    def add_player(self,):
        self.player_roster['Name'] = input('Enter New Players Name:')
        self.player_roster['Phone Number'] = input('Enter Players Phone Number:')
        self.player_roster['Jersey Number'] = int(input('Enter Players Jersey Number'))

if __name__ == "__main__":
    player = PlayerDictionary()
    player.add_player()
    player.display_roster()

稍微可维护的解决方案是为Player创建一个类。设置对象的属性并重载 str 函数,例如

class Player(object):
    def __init__(self):
        self.__name = ""
        self.__phone_number = ""
        self.__jersey_number = ""

    @property
    def name(self):
        return self.__name

    @property
    def phone_number(self):
        return self.__phone_number

    @property
    def jersey_number(self):
        return self.__jersey_number

    @name.setter
    def name(self, val):
        self.__name = val

    @phone_number.setter
    def phone_number(self, val):
        self.__phone_number = val

    @jersey_number.setter
    def jersey_number(self, val):
        self.__jersey_number = val

    def __str__(self):
        return ("Name: %s\nPhone Number: %s\nJersey Number: %s" % (str(self.__name), str(self.__phone_number), str(self.__jersey_number)))

if __name__ == "__main__":
    player = Player()
    player.name = input('Enter New Players Name:')
    player.phone_number = input('Enter Players Phone Number:')
    player.jersey_number = int(input('Enter Players Jersey Number'))
    print(player)

答案 2 :(得分:0)

我建议您将print语句替换为:

print(" Name: %s \n Phone Number: %s \n Jersey Number: %d") % player_roster[x]