Wesley
Wesley

Reputation: 1482

Most efficient way to populate dictionary keys with dictionary

Let's say for example I have 3 friends, John, Carter, Bill and I want to track places they have visited. The places are in a dictionary, if they have visited the place, it will have a value of 1, and 0 if they have not.

places = {"LA": 0, "San Jose": 0, "NY": 0}

Now setting this won't work because it's a shallow copy:

friends = {"John": places, "Carter": places, "Bill": places}

The simple solution I have right now is this:

friends = {"John": {"LA": 0, "San Jose": 0, "NY": 0}, "Carter": {"LA": 0, "San Jose": 0, "NY": 0}, "Bill": {"LA": 0, "San Jose": 0, "NY": 0}}

which doesn't seem very efficient. Is there a better way to do what I am trying to achieve in Python? Either for the syntax of populating friends or just a new method entirely?

Upvotes: 2

Views: 211

Answers (3)

sthede
sthede

Reputation: 928

If 'John' had only visited for example 'LA' and 'NY', couldn't you do this?

"John": {"LA", "NY"}, "Carter": {"San Jose"}, etc...

What would be even more effecient would be to reference index to a list of places, so instead of the names of the places, just a list of indexes, so 'John' would be 0 and 2.

Upvotes: 1

pkacprzak
pkacprzak

Reputation: 5619

If you have a static set of cities, then you could store in a map city name as a key and index of that city as a value. In addition, for each person you can store a list of visits, where i-th element of that list denotes the number of visits in i-th city:

places = {"LA": 0, "San Jose": 1, "NY": 2}
friends = {"John": [0, 0, 0], "Carter": [0, 0, 0], "Bill": [0, 0, 0]}

then if John visits NY you do:

friends["John"][places["NY"]] += 1

It's more memory efficient than your method, because it stores names of cities in one place

Upvotes: 3

dstromberg
dstromberg

Reputation: 7187

I believe you're looking for copy.deepcopy().

friends = {
   "John": copy.deepcopy(places), 
   "Carter": copy.deepcopy(places), 
   "Bill": copy.deepcopy(places),
   }

Upvotes: 1

Related Questions