Working with dictionaries and keys help please!

Steve D'Aprano steve+python at pearwood.info
Thu Jun 1 05:11:00 EDT 2017


On Thu, 1 Jun 2017 10:29 am, David D wrote:

> I have a dictionary with a 10 people, the key being a number (0-10) and the
> value being the people's name.  I am in the processing of Insert, Adding and
> deleting from the dictionary.  All seems well until I delete a person and add
> a new one.  The numbers (keys) do not change and so I am getting an
> non-sequential set of numbers for the keys.  Is there a way of performing this
> where the key will update so that is continues to work sequentially?  Here is
> what I mean
> 
> Print dictionary
> {0 John, 1 David, 2 Phil, 3 Bob}
> 
> remove 1 David
> {0 John, 2 Phil, 3 Bob}
> 
> How can I get it so that the VALUE will reset and it will look like this after
> both adding or deleting?
> 
> {0 John, 1 Phil, 2 Bob}


You can't. That's not how dicts work.

The dictionary key is similar to the primary key in a database. The fact that
they start off as sequential values is irrelevant. Imagine that you create an
account for Phil, and he gets account number 2; then Bob gets account number 3:

print(accounts)
=> {0: John, 1: David, 2: Phil, 3: Bob}

Then you delete David's account. Then Phil calls you, tells you his account
number is 2, and you access Bob's records instead of Phil's!

Database keys should never be changed or reused.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list