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

cvxl0en2  于 2022-12-05  发布在  其他
关注(0)|答案(2)|浏览(134)

我正在编写一个将两个Json文件读入字典的脚本
这两本词典或多或少是相似的,就像这样

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

到目前为止,我一直假设element_id从0开始,并以1递增。然后,要求发生了变化,这次它们从0开始,以4递增,或者类似于以下内容
无论如何,我认为到目前为止,两个字典将有相同数量的元素和相同的增加距离,所以当我在我的脚本中得到元素时,我写了这样的东西

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

但是,要求再次发生变化
现在,一个字典的元素数量不一定与另一个相同,而且也不能保证其中一个总是从0开始
因此,现在我必须在两个字典中找到具有 * 相同元素id* 的元素
所以我的问题是,在上面这样的字典中(来自json),有没有一种***快速***的方法来找到具有特定element_id的元素并获得该元素?
比如

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

它必须是快速的,因为我用它来制作动画

t1rydlwq

t1rydlwq1#

如果需要在字典中查找具有特定element_id的多个元素,并且希望尽可能高效地完成此操作,则可以使用字典存储具有给定element_id的元素。然后,当需要查找具有特定element_id的元素时,只需使用element_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']

    # 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)

这种方法比遍历字典中的元素并检查每个元素的element_id值更有效,因为它只需要遍历字典中的元素一次就可以创建elements_by_id字典,然后就可以在恒定的时间内查找具有特定element_id的元素。
如果你想让代码运行得更快,你可以使用dict.setdefault()方法创建elements_by_id字典,一次遍历字典中的元素。如果你要查找的键在字典中不存在,这个方法允许你指定一个默认值,这样你就不必在添加键到字典之前检查它是否存在。
下面是一个如何使用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)

这个方法比前面的方法更快,因为它只需要对字典中的元素进行一次遍历,并且在添加element_id之前不需要检查它是否已经是字典中的键。

jw5wzhpr

jw5wzhpr2#

使用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)

相关问题