首页 > 解决方案 > 如何访问每一行熊猫字典的值

问题描述

我从数据集创建字典,现在我想访问字典的每一行。这本词典的每一行都包含 2 个名字,例如:Winner: Alex Loser: Leo。我的问题是我不知道如何通过索引访问这两个名称。

我想要这样的东西:
第 1 行:获胜者:Alex Loser:Leo,我想访问这样的行:dictionary[x] -> 所以我可以获取该行,然后一旦我有了我想要访问的行它就像 a=raw[y] 和 b=raw[y+1]。然后我想打印 A 和 B。我想这样做是因为我必须从每一行中复制一个特定的玩家并将其保存到另一个字典中。

这是我为创建字典和访问它而编写的代码,但不能按我的意愿工作。

dicti= imd4.to_dict('index') // dicti  is the dictionary that I created and imd4 is the dataset containing the Winner and the Loser name
for x in dicti:
print (x,':')
for y in dicti[x]:
    a=dicti[x][y]
    b=dicti[x][y+1]    //I can't do this  but I would like to do it. So I can save the data base on their index 
    print (y,':',dicti[x][y])
    print('Test :' ,a)

在这里您可以看到数据集是如何构建 的。提前感谢您的帮助。

标签: pythonpandasmachine-learning

解决方案


让我们设置一个测试字典:

test_dictionary=[
     {'winner':'ross','loser:'chandler'},
     {'winner':'rachael','loser:'phoebe'},
     {'winner':'joey','loser:'monica'},
     {'winner':'gunther','loser:'chandler'}
]

我们可以轻松循环:

for contest in test_dictionary:
    print (contest)

我们可以使用 enumerate 函数添加行号:

for line_number, contect in test_dictionary:
    print (line_number,contest)

所以现在我们有了可以轻松访问下一个元素的行号 - 我们必须记住,虽然我们不想访问最后一个元素,因为在此之后我们无法打印比赛所以我们循环到 [-1 ] 元素:

for line_number, contect in test_dictionary[:-1]:
    print (line_number,contest)
    print (line_number+1,test_dictionary[line_number+1])

我们也可以简单地使用 test_dictionary 的长度范围并直接访问元素:

for line_number in range(len(test_dictionary)-1]:
    print (line_number,test_dictionary[line_number])
    print (line_number+1,test_dictionary[line_number+1])

推荐阅读