python - 我有一个列表,其中包含更多字典,想要删除其中一个,但该字典是动态的

标签 python python-3.x list dictionary

所以我有一个列表,其中有一些字典,我有一个函数,用 2 个输入询问哪个字典添加, 然后我有另一个带有 1 个输入的函数,其中 dict 被删除,可以这样做吗?

my_list = [{"a":"b"},{"c":"d"}]

def add_dict():
    my_dict = {}
    add_key = input("insert key : ")
    add_value = input("insert value: ")
    my_dict[add_key] = add_value
    return my_list.append(my_dict)

如果我添加像 {"e":"f"} 这样的东西

my_list = [{"a":"b"},{"c":"d"},{"e":"f"}]

我需要一个函数来删除像 {"c":"d"} 这样的字典

def remove_dict():
  delete = input("with dict want remove? ")

结果应该在哪里

my_list = [{"a":"b"},{"e":"f"}]

最佳答案

假设您只是想通过指定字典的键来删除值,您可以执行以下操作:

def remove_dict():
    delete_value = str(input("with dict want remove? "))
    for i in range(len(my_list)-1):
        if list(my_list[i].keys()) == [delete_value]:
            del my_list[i]

只需根据要求指定字母,它就会从您的词典列表中删除该值。

例如:

my_list = [{"a":"b"},{"c":"d"},{"e":"f"}]
my_list
[{'a': 'b'}, {'c': 'd'}, {'e': 'f'}]

remove_dict()
with dict want remove? c

my_list
[{'a': 'b'}, {'e': 'f'}]

请注意:按照其设置方式,您不需要在输入中使用引号 (' ')。

如果您想指定整个字典值(即 {"c":"d"}),那么这将起作用:

def remove_dict():
delete_value = input("with dict want remove? ")
for i in range(len(my_list)-1):
    if str(my_list[i]) == delete_value:
        del my_list[i]

然后你会得到:

remove_dict()
with dict want remove? {'c': 'd'}

my_list
[{'a': 'b'}, {'e': 'f'}]

关于python - 我有一个列表,其中包含更多字典,想要删除其中一个,但该字典是动态的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60469346/

相关文章:

python - 提取字典中的值

python - pandas groupby 作为列表返回空,同时使用 agg 和 apply 函数

list - 从无限列表中获取所有长度为 4 的子串

python - Matlab 与 Python : Reshape

python - 与 Python 的流畅界面

python - Plotnine 的比例填充和轴位置

python - pandas 在每个组中找到满足特定条件的行的索引并为这些行分配值

python - 寻找一种更优雅(更少代码)的方式来比较多个字典

python - 如何在 python docx 中将修改的段落加粗

python - 编写一个在列表索引之间交替加号和减号的函数