父亲儿子字典与用户的选项和输出儿子,父亲或者祖父的名字的名字

时间:2013-11-21 23:01:10

标签: python dictionary

我正在尝试将此文件转换为两个字典,以便用用户的输入进行访问,而我完全迷失了。可悲的是我一直在这几个星期的现在。我有文件读取,并知道如何设置输入选项,而不是如何根据用户选项和名称获取某个名称。

到目前为止,这是我的代码:

sonfather = {}
fatherson = {}
names = open('names.dat', 'r')
sonfather = names.read().split(',')

print sonfather

print "Father/Son Finder"
print "0 - Quit"
print "1 - Find a Father"
print "2 - Find a Grandfather"
print "3 - Find a Son"
print "4 - Find a Grandson"
print "5 - List of names"

control = ""
while control != "quit":
    choice = input("Enter your choice here: ")
    if choice == 0:
        control = "quit"
    elif choice == 1:
        print input("Enter the name of the son :")

1 个答案:

答案 0 :(得分:0)

names = open('names.dat', 'r')
sonfather = names.read().split(',')
print sonfather

您必须了解对象的类型,才能正确使用与其相关的任何字典。因为你不会得到字典类型的东西,除非它是字典类型。

sonfather时{p> print是一个列表。它是一个包含字符串的列表。

你需要对该列表进行SOMETHING,将其“更改”为字典。仅仅因为它有"KEY:VALUE"它并不意味着它是一本字典。它是一个字符串。

对于初学者来说,你可能只想将它们分别放在冒号上。

sonfather = [x.split(':') for x in sonfather]

这个[x for x in blabla]的东西是列表理解,它可能是一个小小的高级...但它做的事情与此相同:

new_sonfather = []
for item in sonfather:
    new_sonfather.append(item.split(":"))
sonfather = new_sonfather

这会迭代sonfather中的每个项目替换它(注意高级pythonistas:我知道并非真的...),此表单中的列表"son:father"变为['son','father']

然后你有一些看起来像这样的东西

sonfather = [['son1','father1'],['son2','father2'],['son3','father3'],['son4','father4']]

这几乎是您想要的地方。

然后它在这里变得非常神奇。

从这里将该sucker转换为字典

son_father_dictionary = dict(sonfather)

aww啪的一声。

在这一点上son_father_dictionary是一张真正的官方卡片,载有字典俱乐部的成员。

所以,如果你要做一些疯狂的事情:

print(son_father_dictionary['son1'])

输出为father1

相关问题