Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionaries in Python

Tags:

python

What do these two statements 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 am guessing that the first statement assigns clust[i].id and clust[j].id keys of the distances map to the result of the distance(..) function. However, I am confused since lists are represented using [] and dictionaries using {} in Python. What's the correct answer?

like image 912
Dhruv Avatar asked Dec 17 '22 11:12

Dhruv


2 Answers

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

like image 70
Ignacio Vazquez-Abrams Avatar answered Dec 28 '22 23:12

Ignacio Vazquez-Abrams


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

distances is a dictionary where keys are tuples of 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 just assigned to that distance, accessing the dictionary value just assigned. other answers provide the summary of what's a dictionary.

like image 21
BrainStorm Avatar answered Dec 29 '22 01:12

BrainStorm