Posted under » Python » Django on 24 May 2022
Python Collections (Arrays). There are four collection data types in the Python programming language:
You can use dict to count duplicates.
To create a dictionary, the brackets turn curly. In PHP it is called an associative array and uses arrow (in PHP) instead colon in Python.
If you need more info of what you can do the collections,
print(dir(alist))
af = {'ahmad' : 'WENDY', 'sollihin' : 'CHOOI LENG'}
Please note the dictionary key (the first part 'ahmad') must be string. Looping for dictionary
for x in af : print(x, "->", af[x])
To begin, we initialise the list. If it is a set, the we do {} instead of []
cars=[]
Or straight away add some values.
cars = ["Ford", "Volvo", "BMW"]
Use the len() method to return the length of an array (the number of elements in an array) or query.
x = len(cars) 3
This is similar to PHP and django count()
To show a value = BMW
print(cars[2])
To know the number 2 or position of the list
print(index.cars('BMW'))
cars.sort() print(cars)
Looping to show all values
for x in cars: print(x)
You can use the append() method to add an element to an array.
cars.append("Honda")
Removing Array Elements by pop or remove
cars.pop(1) #2nd element cars.remove("Volvo")
For List filter and finding duplicates
For PHP array.
See also Show all rows in Django template.