Dictionaries in Python

What do these two expressions mean in Python?

distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec) d=distances[(clust[i].id,clust[j].id)] 

I assume that the first statement assigns the keys clust[i].id and clust[j].id distance map to the result of the distance(..) function. However, I got confused as lists are represented using [] and dictionaries using {} in Python. What is the correct answer?

+4
source share
3 answers
 distances[(clust[i].id,clust[j].id)]=distance(clust[i].vec,clust[j].vec) 

distances - a dictionary where the keys are tuples , probably integers, and the value is the distance measured between them by the distance function. in the second line:

 d=distances[(clust[i].id,clust[j].id)] 

the d variable is simply assigned to this distance, getting the dictionary value just assigned. other answers contain a summary of the dictionary.

+4
source

Dictionary literals use {} . Indexing operations use [] , regardless of type.

+6
source

Hope this makes it clear:

 >>> a = {} >>> a[1] = 2 >>> a[(1, 2)] = 3 >>> a {(1, 2): 3, 1: 2} 
+2
source

All Articles