简体   繁体   中英

How can i add the dictionary into list using append function or the other function?

Execusme, i need your help!

Code Script

tracks_ = []
track = {}

if category == 'reference':
  for i in range(len(tracks)):
    if len(tracks) >= 1:
      _tracks = tracks[i]
      track['id'] = _track['id']
      tracks_.append(track)
  print (tracks_)

tracks File

[{'id': 345, 'mode': 'ghost', 'missed': 27, 'box': [0.493, 0.779, 0.595, 0.808], 'score': 89, 'class': 1, 'time': 3352}, {'id': 347, 'mode': 'ghost', 'missed': 9, 'box': [0.508, 0.957, 0.631, 0.996], 'score': 89, 'class': 1, 'time': 5463}, {'id': 914, 'mode': 'track', 'missed': 0, 'box': [0.699, 0.496, 0.991, 0.581], 'score': 87, 'class': 62, 'time': 6549}, {'id': 153, 'mode': 'track', 'missed': 0, 'box': [0.613, 0.599, 0.88, 0.689], 'score': 73, 'class': 62, 'time': 6549}, {'id': 588, 'mode': 'track', 'missed': 0, 'box': [0.651, 0.685, 0.958, 0.775], 'score': 79, 'class': 62, 'time': 6549}, {'id': 972, 'mode': 'track', 'missed': 0, 'box': [0.632, 0.04, 0.919, 0.126], 'score': 89, 'class': 62, 'time': 6549}, {'id': 300, 'mode': 'ghost', 'missed': 6, 'box': [0.591, 0.457, 0.74, 0.498], 'score': 71, 'class': 62, 'time': 5716}]

Based on the codescript and the input above, i want to print out the tracks_ and the result is

[{'id': 300}, {'id': 300}, {'id': 300}, {'id': 300}, {'id': 300}, {'id': 300}, {'id': 300}]

but, the result that print out should be like this :

[{'id': 345}, {'id': 347},{'id': 914}, {'id': 153}, {'id': 588}, {'id': 972}, {'id': 300}, ]

you are appending to your list track_ the same dict , which causes to have in your list only references of the same dict, practically you have only one dict in your list tracks_ , and any modification to the dict track will be reflected in all the elements of your list, to fix you should create a new dict on each iteration:

if category == 'reference' and len(tracks) >= 1:
    for d in tracks:
            tracks_.append({'id' : d['id']})

you could use a list comprehension:

tracks_ = [{'id': t['id']} for t in tracks]
tracks_

output:

[{'id': 345},
 {'id': 347},
 {'id': 914},
 {'id': 153},
 {'id': 588},
 {'id': 972},
 {'id': 300}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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