I tried to remove duplicates of a list using set
method and add that value with a key to an empty python dictionary.
But it gives me that error message
TypeError: list indices must be integers or slices, not str
I tried this way:
mydir =[]
person_trackID = "p7"
class_ids = [3 ,3 ,3 ]
print(mydir,person_trackID,set(class_ids))
mydir[person_trackID] = list(set(class_ids))
print(mydir)
please help me to solve this.Thank you
You are declaring a list here mydir = []
Change it to dictionary mydir = {}
you are doing great with one little mistake. you are declaring 'mydir' as a python list and giving it 'p7' as an index. Python list can't have string indexes. you can change the first line to following.
mydir = {}
You are trying to insert an item into mydir
at index 'p7'
(which is a string). Indices are integers and not strings . That is why the error.
Your question says that you want to insert into a dictionary
and your code uses a list
.
mydir = {}
- This is a dictionary
mydir = []
- This is a list
Here is what you need to do:
mydir = {}
person_trackID = "p7"
class_ids = [3 ,3 ,3 ]
print(mydir,person_trackID,set(class_ids))
mydir[person_trackID] = list(set(class_ids))
print(mydir)
{} p7 {3}
{'p7': [3]}
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.