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

2021-09-27 05:37:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我的输入示例如下:

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)