为什么我的字典以错误的顺序打印,因为它的迭代输入?

时间:2016-02-01 10:59:48

标签: python dictionary nested

我的示例输入如下:

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."

我正在尝试以下列格式将此信息输入到字典中,例如:{'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)

1 个答案:

答案 0 :(得分:2)

Dict不是有序类型。

如果您需要,可以使用OrderedDict()库中的collections