Python 如何访问字典列表的索引?

Python 如何访问字典列表的索引?,python,dictionary,Python,Dictionary,假设我给你一个字典列表,在哪里 dict1 = dict(a = 2, b = 5, c = 7) dict2 = dict(c = 5, d = 5, e = 1) dict3 = dict(e = 2, f = 4, g = 10) list_of_dictionaries = [dict1, dict2, dict3] 我如何才能找到最高索引(又称最新字典)的值 因此,如果我要编写一个方法从字典列表中删除一项,那么假设我要从字典中删除c 我如何才能从第二个字典而不是第一个字典中删除c?键

假设我给你一个字典列表,在哪里

dict1 = dict(a = 2, b = 5, c = 7)
dict2 = dict(c = 5, d = 5, e = 1)
dict3 = dict(e = 2, f = 4, g = 10)
list_of_dictionaries = [dict1, dict2, dict3]
我如何才能找到最高索引(又称最新字典)的值

因此,如果我要编写一个方法从字典列表中删除一项,那么假设我要从字典中删除
c


我如何才能从第二个字典而不是第一个字典中删除c?

键通过反向索引在列表中反向(
a_list[::-1]
)。 从那里,一旦您找到任何符合需求的字典,就修改它并退出函数或循环-因此早期的
return
s

此代码:

def get_last(bucket,key):
  for d in bucket[::-1]:
    if key in d.keys():
      return d[key]
  return None

def set_last(bucket,key,val):
  for d in bucket[::-1]:
    if key in d.keys():
       d[key] = val
       return

def pop_last(bucket,key):
  out = None
  for d in bucket[::-1]:
    if key in d.keys():
      return d.pop(key)

dict1 = {'a': 2, 'b': 5, 'c': 7}
dict2 = {'c': 5, 'd': 5, 'e': 1}
dict3 = {'e': 2, 'f': 4, 'g': 10}
list_of_dictionaries = [dict1, dict2, dict3]

print get_last(list_of_dictionaries ,'c')
set_last(list_of_dictionaries ,'c',7)
print list_of_dictionaries 
popped = pop_last(list_of_dictionaries ,'c')
print popped
print list_of_dictionaries
给出:

5
[{'a': 2, 'c': 7, 'b': 5}, {'c': 7, 'e': 1, 'd': 5}, {'e': 2, 'g': 10, 'f': 4}]
7
[{'a': 2, 'c': 7, 'b': 5}, {'e': 1, 'd': 5}, {'e': 2, 'g': 10, 'f': 4}]

我不太清楚你的意思,但我想向你展示一些可能有用的东西:

首先,您的词典应该是这样的:

dict1 = {"a" :2, "b" : 5, "c" :7}
dict2 = {"c" :5, "d" :5, "e" :1}
dict3 = {"e" :2, "f" :4, "g" :10}
然后你问:“我怎样才能从第二本字典而不是第一本字典中删除c?”

您可以通过以下方式删除它:

del dict2["c"]

首先,你对字典的定义可能会失败。对此我很抱歉!修复。您也可以通过删除“python”标记来“修复”它。要构建python字典,它应该是:
dict1=dict(a=2,b=5,c=7)
,或者
dict1={'a':2,'b':5,'c':7}