2016-02-01 64 views
1

我的例子输入如下:为什么我的字典按照迭代的输入顺序打印错误?

example_input = "John is connected to Bryant, Debra, Walter.\ 
John likes to play The Movie: The Game, The Legend of Corgi, Dinosaur Diner.\ 
Bryant is connected to Olive, Ollie, Freda, Mercedes.\ 
Bryant likes to play City Comptroller: The Fiscal Dilemma, Super Mushroom Man.\ 
Mercedes is connected to Walter, Robin, Bryant.\ 
Mercedes likes to play The Legend of Corgi, Pirates in Java Island, Seahorse Adventures.\ 
Olive is connected to John, Ollie.\ 
Olive likes to play The Legend of Corgi, Starfleet Commander.\ 
Debra is connected to Walter, Levi, Jennie, Robin.\ 
Debra likes to play Seven Schemers, Pirates in Java Island, Dwarves and Swords.\ 
Walter is connected to John, Levi, Bryant.\ 
Walter likes to play Seahorse Adventures, Ninja Hamsters, Super Mushroom Man.\ 
Levi is connected to Ollie, John, Walter.\ 
Levi likes to play The Legend of Corgi, Seven Schemers, City Comptroller: The Fiscal Dilemma.\ 
Ollie is connected to Mercedes, Freda, Bryant.\ 
Ollie likes to play Call of Arms, Dwarves and Swords, The Movie: The Game.\ 
Jennie is connected to Levi, John, Freda, Robin.\ 
Jennie likes to play Super Mushroom Man, Dinosaur Diner, Call of Arms.\ 
Robin is connected to Ollie.\ 
Robin likes to play Call of Arms, Dwarves and Swords.\ 
Freda is connected to Olive, John, Debra.\ 
Freda likes to play Starfleet Commander, Ninja Hamsters, Seahorse Adventures." 

我想输入此信息将在以下格式的词典,e.g:{'John':{'connected':[],'likes':[]}}并设法让名字的字典,他们连字典。但是,我无法填写connectedlikes列表,因为当我遍历我的get_name函数时,返回的顺序就搞砸了,使我很难将正确的信息添加到字典中。

这里是我的代码:

def get_name(string_input): 
    l = [line.split('is connected to') for i, line in enumerate(string_input.split('.')) if i % 2 == 0] 
    name = {} 
    names = {name[0]:{'connected':[],'likes':[]} for name in l} 
    return names 

print get_name(example_input) 
+6

词典默认情况下为未命令类型。考虑使用有序的字典,如果它对你很重要。 – AlokThakur

+0

使用有序字典。 https://docs.python.org/2/library/collections.html#ordereddict-objects –

回答

2

快译通不是一个有序的类型。

如果您需要订购,请使用collections库中的OrderedDict()

+0

这应该是一个评论,而不是答案。 –

+0

对于这个问题,这是一个完全有效的答案 – Mel

相关问题