简体   繁体   English

如何在 python 中创建对象数组

[英]How to create array of objects in python

I'm creating a dictionary in python.我正在 python 中创建字典。 I'm getting same objects stored in dictionary while I loop through object.当我循环通过 object 时,我将相同的对象存储在字典中。 Where am I doing wrong?我在哪里做错了?

I tried dict() , however, I'm avoiding dict() .我尝试了dict() ,但是,我避免dict()

Code I've tried is here:我试过的代码在这里:

image_dict = {}
#query for getting objects
images = Image_history.objects.all()
for image in images:
    image_history = dict({
        "type": image.image_type,
        "timestamp": image.last_updated_timestamp,
     })
image_dict.append(image_history)

My problem is when I use this following method to create dictionary in python:我的问题是当我使用以下方法在 python 中创建字典时:

    image_dict = {}
    image_list = {}
    # list of image_details
    image_list["image_details"] = [] 
    #query for getting objects
    images = Image_history.objects.all() 
    #looping through object and storing in dictionary
    for image in images:
       image_dict['type']= image.image_type
       image_dict['timestamp']= image.last_updated_timestamp
       #appending all those objects in loop to image_list
       image_list["image_details"].append(image_dict)

I expect the output to be a list of different objects.我希望 output 是不同对象的列表。 But, I'm getting list of same duplicate objects.但是,我得到了相同重复对象的列表。 Expected output:预期 output:

{
    "image_detail":[
        {
            "type": "png",
            "timestamp": "1-12-18"
        },
        {
            "type": "jpeg",
            "timestamp": "1-1-19"
        }
   ]
}

Actual output I'm getting:实际 output 我得到:

{
    "image_detail":[
        {
            "type": "jpeg",
            "timestamp": "1-1-19"
        },{
            "type": "jpeg",
            "timestamp": "1-1-19"
        }
     ]
}

Edit your code to:将您的代码编辑为:

image_list = {}
# list of image_details
image_list["image_details"] = [] 
#query for getting objects
images = Image_history.objects.all() 
#looping through object and storing in dictionary
for image in images:
   image_dict = {}
   image_dict['type']= image.image_type
   image_dict['timestamp']= image.last_updated_timestamp
   #appending all those objects in loop to image_list
   image_list["image_details"].append(image_dict)

Your are editing the same dictionary object, you just have to create new one at each iteration.您正在编辑同一个字典 object,您只需在每次迭代时创建一个新字典。 Dictionary (created using dict or {} ) is mutable objects in python, I suggest you read more about mutability in python.字典(使用dict{}创建)是 python 中的可变对象,我建议您阅读有关 python 中的可变性的更多信息。 And I suggest more compact way to build your list, using list comprehensions:我建议使用更紧凑的方式来构建您的列表,使用列表推导:

   image_list["image_details"] = [
       {
           'type': image.image_type, 
           'timestamp': image.last_updated_timestamp
       } for image in images
   ]

Note: you can create immutable dictionary in python, but this off-topic.注意:您可以在 python 中创建不可变字典,但这离题了。

You are mutating the same image_dict object, which in turn modifies existing references to that object (ie previous dictionary values).您正在改变相同的image_dict object,这反过来又修改了对该 object 的现有引用(即以前的字典值)。

Why do you avoid constructing a new dict ?你为什么避免构建一个新的dict It is the only way to create separate dictionaries.这是创建单独字典的唯一方法。

Alternatively you can move image_dict = {} into the for loop:或者,您可以将image_dict = {}移动到for循环中:

...
for image in images:
    image_dict = {}
    image_dict['type']= image.image_type
    ...

You need to use a copy of image_history dict as otherwise, you are just adding multiple references of the same dict.您需要使用image_history dict 的副本,否则,您只是添加了同一 dict 的多个引用。 In case of not using image_history.copy() you will find each element in the image_dict to have the same value as the last image object in the for loop.在不使用image_history.copy()的情况下,您会发现 image_dict 中的每个元素与for循环中的最后一个图像image_dict具有相同的值

Try the following.试试下面的。 I have used dict.update() .我用过dict.update() I am also using the index derived from enumeration of the images .我还使用从images枚举中得出的索引。 An additional benefit of this approach is that you could easily load it up as a dataframe to view the data.这种方法的另一个好处是您可以轻松地将其加载为 dataframe 以查看数据。

image_dict = dict()
#query for getting objects
images = Image_history.objects.all()
for i, image in enumerate(images):
    image_history = {
                     "type": image.image_type,
                     "timestamp": image.last_updated_timestamp,
                     }
image_dict.update({i: image_history.copy()})

# Optionally visualize the data in a dataframe
import pandas as pd
df = pd.DataFrame(image_dict).T
df.head()

Dict Comprehension听写理解

Concise version of your code using dict comprehension.使用 dict 理解的代码的简洁版本。

# dict of image_history dicts
image_dict = dict((i, {"type": image.image_type, 
                       "timestamp": image.last_updated_timestamp, 
                       }) for i, image in enumerate(images))

List Comprehension列表理解

Concise version of your code using list comprehension.使用列表理解的代码的简洁版本。

# list of image_history dicts
image_list = [{"type": image.image_type, 
               "timestamp": image.last_updated_timestamp, 
               }) for image in images)

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

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