在字典中添加条目之前,如何检查重复的条目

时间:2018-07-24 07:33:05

标签: python

鉴于我有以下字典,用于存储键(entry_id),值(entry_body,entry_title)对。

"entries": {
    "1": {
            "body": "ooo",
            "title": "jack"
        },
    "2": {
            "body": "ooo",
            "title": "john"
        }
}

如何检查要添加到字典中的条目的标题是否已经存在。 例如:这是我要添加的新条目。

{
    "body": "nnnn",
    "title": "jack"
}

4 个答案:

答案 0 :(得分:8)

您是否考虑过更改数据结构?没有上下文,条目的ID似乎没有用。您的问题建议您只想存储唯一的标题,那么为什么不将它们作为您的密钥呢?

示例:

if newname in entries

这样,您就可以进行有效的"entries": { "jack": { "body": "ooo", "id": 1 }, "john": { "body": "ooo", "id": 2 } } 成员资格测试。

编辑:

根据您的评论,您仍然可以通过扩展数据结构来保留ID:

{{1}}

答案 1 :(得分:1)

这应该起作用吗?

entry_dict = {
    "1": {"body": "ooo", "title": "jack"},
    "2": {"body": "ooo", "title": "john"}
}

def does_title_exist(title):
    for entry_id, sub_dict in entry_dict.items():
        if sub_dict["title"] == title:
            print("Title %s already in dictionary at entry %s" %(title, entry_id))
            return True
    return False

print("Does the title exist? %s" % does_title_exist("jack"))

正如克里斯蒂安建议的那样,这似乎是工作的低效率数据结构。似乎如果您只需要索引ID,则列表可能会更好。

答案 2 :(得分:1)

我同意@ChristianKönig的回答,您的数据结构似乎可以变得更加清晰和高效。不过,如果您特别需要对此设置的解决方案,那么可以使用以下解决方案-它会自动向Private Sub cmdBrowse_Click() 'myFile = Application.GetOpenFilename(, , "Select a File.") Dim fname As String Dim fpath As String fpath = ThisWorkbook.Path With Application.FileDialog(msoFileDialogOpen) .InitialFileName = fpath .ButtonName = "Get File Name" .Title = "File Selection" .Filters.Clear .Filters.Add "Excel Files", "*.xl; *.xlsx; *.xlsm; *.xlb; *.xlam; *.xltx; *.xltm; *.xls; *.xla; *.xlt; *.xlm; *.xlw" .AllowMultiSelect = False If .Show = True Then fname = .SelectedItems(1) Me.txtbxSelectFile.Text = fname Else MsgBox "Operation Canceled" Unload Me End If End With End Sub Private Sub cmdbtnOpen_Click() Do While txtbxSelectFile = "" MsgBox "Please Select a file", vbOKOnly, "No File Selected" Loop Workbooks.Open Me.txtbxSelectFile Unload Me selectRangefrm.Show End Sub 字典添加新的整数键。

我添加了一个额外的案例,以显示拒绝和接受的更新。

entries

输出:

def existing_entry(e, d):
    return [True for entry in d["entries"].values() if entry["title"] == e["title"]]

def update_entries(e, entries):
    if not any(existing_entry(e, entries)):
        current_keys = [int(x) for x in list(entries["entries"].keys())]
        next_key = str(max(current_keys) + 1)
        entries["entries"][next_key] = e
        print("Updated:", entries)
    else:
        print("Existing entry found.")

update_entries(new_entry_1, data)
update_entries(new_entry_2, data)

数据:

Existing entry found.
Updated: 
{'entries': 
    {'1': {'body': 'ooo', 'title': 'jack'}, 
     '2': {'body': 'ooo', 'title': 'john'}, 
     '3': {'body': 'qqqq', 'title': 'jill'}
    }
}

答案 3 :(得分:0)

我认为要实现这一目标,就得遍历字典。

'john' in [the_dict[en]['title'] for en in the_dict]
相关问题