根据索引从字典python中删除一个元素

时间:2019-04-02 17:34:40

标签: python python-3.x dictionary

如何根据索引从字典中删除元素? 例如,如果我有

dict = {'s':0, 'e':1, 't':6}

我要删除并返回's'和0,以使字典具有

dict = {'e':1, 't':6}

我尝试过dictionary.popitem()可以从字典中删除't':6, dictionary.pop(key)来删除键,但是我无法找到要删除的键,只有索引。

2 个答案:

答案 0 :(得分:1)

假设您在订购了dict键的Python 3.7或更高版本中执行此操作,则可以从dict键创建一个迭代器,并使用next函数获取第一个键,以便可以使用del语句以删除该密钥:

d = {'s':0, 'e':1, 't':6}
del d[next(iter(d))]
print(d)

这将输出:

{'e': 1, 't': 6}

如果要删除其他索引的键,则可以使用itertools.islice获取给定索引的键。例如,要从d中删除第二个关键字(索引1):

from itertools import islice
d = {'s':0, 'e':1, 't':6}
del d[next(islice(d, 1, None))]
print(d)

这将输出:

{'s': 0, 't': 6}

答案 1 :(得分:0)

您可以通过迭代字典来做到这一点。

1)如果您只有一个索引要删除

dict = {'s':0, 'e':1, 't':6}

i = 0
for key in dict.keys():
    if i == 1: #assuming you want to remove the second element from the dictionary
        key_to_delete = key
    i = i + 1
if key_to_delete in dict: del dict[key_to_delete]

print(dict)

2)如果要删除多个索引:

dict = {'s':0, 'e':1, 't':6}

i = 0
index_to_delete = [1,2] #assuming you want to remove the second and the third elements from the dictionary
keys_to_delete = []
for key in dict.keys():
    if i in index_to_delete:
        print(key)
        keys_to_delete.append(key)
    i = i + 1

for key in keys_to_delete:
    if key in dict:
        del dict[key]

print(dict)