python - 为什么我的字典在迭代输入时以错误的顺序打印?

标签 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)

最佳答案

Dict 不是有序类型。

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

关于python - 为什么我的字典在迭代输入时以错误的顺序打印?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35128817/

相关文章:

python - 在 MacOS 上创建 conda 环境失败 : ResolvePackageNotFound

python - 我可以从标准选项卡遍历中排除特定 Controller 吗?

jquery - 我需要一个方便的 jQuery 工具(插件)来处理 map

python - 如何从 Python shell 调用内部函数?

python - 在 python 中复制文本文件的最后三行?

python - 在Python中比较列表/字典中单词的最有效方法

java - 如何检查 java map 包含什么类型的数据?

swift - 快速对两个值进行字典排序

jquery - 循环嵌套对象

javascript - JavaScript 中的嵌套 for 循环