简体   繁体   English

在 Json 数组(数组字典)中搜索元素的有效方法

[英]An efficient way to search elements in a Json array (dictionary of arrays)

I am writing a script that reads two Json files into dictionaries我正在编写一个脚本,将两个 Json 文件读入字典

The dictionaries are more or less similar, like this字典或多或少是相似的,就像这样

{  "elements":[
    {
     "element_id":0,
     "thedata":{
                "this": 5
               }
     },
     {
     "element_id":4,
     "thedata":{
                "this": 5
               }
     }
    {
      ...
    }
]}

So far I had assumed that the element_id went from 0 and increased 1 by 1 Then the requirements changed and this time they went from 0 and increased 4 by 4 or something like this到目前为止,我假设element_id从 0 开始增加 1 到 1 然后要求改变了,这次他们从 0 开始增加 4 到 4 或类似这样

Anyway, I though so far that both dictionaries would have the same number of elements and the same increasing distance so when I got the elements in my script I wrote something like不管怎样,到目前为止,我认为两个词典都有相同数量的元素和相同的递增距离,所以当我在脚本中得到这些元素时,我写了类似

def process_elements(number):
    el1_id=thedictionary['elements'][number]['element_id']
    el2_id=thedictionary2['elements'][number]['element_id']
    assert(el1_id==el2_id)
    #here work with the data 

However the requirements have changed again但是要求又变了

Now the number of elements of one dictionary are not necessarily the same as the other Also it is not guaranteed that one of them start always at 0现在一个字典的元素数量不一定与另一个相同也不能保证其中一个总是从 0 开始

So now I have to find the elements in both dictionaries with the same element id所以现在我必须在两个字典中找到具有相同元素 id 的元素

So my question is, in a dictionary like above (that came from a json) is there a quick way to find the element that has a particular element_id and get the element?所以我的问题是,在上面的字典(来自 json)中,有没有一种快速的方法可以找到具有特定element_id的元素并获取该元素?

Something like就像是

def process_elements(number):
    el1_id=thedictionary['elements'][number]['element_id']

    n=find_i(thedictionary2,el1_id) #finds the index with the element that has id the same as el1_id
    el2_id=thedictionary2['elements'][n]['element_id']
    assert(el1_id==el2_id)  #Of course they are the same since we used find_i
    #here work with the data 

It has to be quick since I use it for an animation它必须很快,因为我将它用于 animation

I don't know why the excellent answer to this question was deleted (and it seems the user too).我不知道为什么删除了这个问题的优秀答案(而且似乎也是用户)。 So I will post the answer here so others can use it.所以我会在这里发布答案,以便其他人可以使用它。 (Credits to Khaoz-07 ) (感谢 Khaoz-07)


If you need to find multiple elements with a particular element_id in a dictionary, and you want to do it as efficiently as possible, you could use a dictionary to store the elements with a given element_id.如果您需要在字典中查找具有特定 element_id 的多个元素,并且希望尽可能高效地执行此操作,则可以使用字典来存储具有给定 element_id 的元素。 Then, when you need to find an element with a particular element_id, you can just look it up in the dictionary using the element_id as the key, without having to iterate over the elements in the dictionary.然后,当您需要查找具有特定 element_id 的元素时,您可以使用 element_id 作为键在字典中查找它,而不必遍历字典中的元素。

Here's an example of how you could do this:这是您如何执行此操作的示例:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Check if the element_id is already a key in the elements_by_id dictionary
    if element_id not in elements_by_id:
        # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,
        # with the element_id as the key and an empty list as the value
        elements_by_id[element_id] = []

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary
# using the element_id as the key
found_elements = elements_by_id[4]

# Print the found elements to the console
print(found_elements)

This method is more efficient than iterating over the elements in the dictionary and checking each element's element_id value, because it only requires a single pass over the elements in the dictionary to create the elements_by_id dictionary, and then you can look up elements with a particular element_id in constant time.这种方法比遍历字典中的元素并检查每个元素的 element_id 值更有效,因为它只需要一次遍历字典中的元素来创建 elements_by_id 字典,然后您可以查找具有特定 element_id 的元素在恒定的时间。

If you want to make the code even faster, you could use the dict.setdefault() method to create the elements_by_id dictionary in a single pass over the elements in the dictionary.如果你想让代码更快,你可以使用 dict.setdefault() 方法来创建 elements_by_id 字典,一次遍历字典中的元素。 This method allows you to specify a default value to use if the key you're looking for doesn't already exist in the dictionary, so you don't have to check if the key exists before adding it to the dictionary.如果要查找的键在字典中不存在,此方法允许您指定要使用的默认值,因此您不必在将键添加到字典之前检查该键是否存在。

Here's an example of how you could use the dict.setdefault() method to create the elements_by_id dictionary:以下是如何使用 dict.setdefault() 方法创建 elements_by_id 字典的示例:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Use the setdefault() method to create a new key-value pair in the dictionary,
    # with the element_id as the key and an empty list as the value, if the element_id is not already a key in the dictionary
    elements_by_id.setdefault(element_id, [])

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can just look it up in the dictionary
# using the element_id as the key
found_elements = elements_by_id[4]

# Print the found elements to the console
print(found_elements)

This method is faster than the previous method because it only requires a single pass over the elements in the dictionary, and it doesn't require you to check if the element_id is already a key in the dictionary before adding it.这种方法比前面的方法更快,因为它只需要一次遍历字典中的元素,并且不需要在添加之前检查 element_id 是否已经是字典中的键。

Alternatively, you can use the dict.get() method to get the list of elements with a given element_id, and specify a default value to return if the element_id doesn't exist as a key in the dictionary.或者,您可以使用 dict.get() 方法获取具有给定 element_id 的元素列表,并指定一个默认值以在 element_id 作为键不存在于字典中时返回。

One advantage of using the dict.get() method to get the list of elements with a given element_id is that it allows you to specify a default value to return if the element_id doesn't exist as a key in the dictionary.使用 dict.get() 方法获取具有给定 element_id 的元素列表的一个优点是,如果 element_id 作为键不存在于字典中,它允许您指定要返回的默认值。

This means you don't have to use the in keyword to check if the element_id exists as a key in the dictionary before trying to access the elements with that id, which can make the code more concise and readable.这意味着在尝试访问具有该 id 的元素之前,您不必使用 in 关键字来检查字典中是否存在 element_id 作为键,这可以使代码更加简洁和可读。 Instead of having to write an if statement to check if the element_id exists as a key in the dictionary, you can just use the dict.get() method to get the list of elements with that id, and specify a default value to return if the element_id doesn't exist.不必编写 if 语句来检查 element_id 是否作为字典中的键存在,您只需使用 dict.get() 方法获取具有该 id 的元素列表,并指定一个默认值以返回 if element_id 不存在。 This can make the code easier to write and maintain, and it can also make it easier to understand what the code is doing.这可以使代码更容易编写和维护,也可以更容易理解代码的作用。

Using the get() method:使用 get() 方法:

# Create a dictionary to store the elements with a given element_id
elements_by_id = {}

# Iterate over the elements in the dictionary
for element in thedictionary['elements']:
    # Get the element_id for the current element
    element_id = element['element_id']

    # Check if the element_id is already a key in the elements_by_id dictionary
    if element_id not in elements_by_id:
        # If the element_id is not already a key in the dictionary, create a new key-value pair in the dictionary,
        # with the element_id as the key and an empty list as the value
        elements_by_id[element_id] = []

    # Add the current element to the list of elements with the given element_id
    elements_by_id[element_id].append(element)

# Now, when you need to find the elements with a particular element_id, you can use the dict.get() method
# to get the list of elements with the given element_id, and specify a default value to return if the element_id
# doesn't exist as a key in the dictionary
found_elements = elements_by_id.get(34554, [])

# Print the found elements to the console
print(found_elements)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM