Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key-value consistency in python dictionaries

Tags:

python

This is probably a noob question. For any dictionary 'd' in python is this always True:

dict( zip( d.keys(), d.values() ) ) == d 

Are the keys and values returned in the same corresponding order ?

like image 385
GeneralBecos Avatar asked Dec 02 '11 23:12

GeneralBecos


People also ask

Can dictionary have same keys with different values?

Duplicate keys are not allowed. A dictionary maps each key to a corresponding value, so it doesn't make sense to map a particular key more than once.

Do Python dictionaries store key-value pairs?

Python's dictionary allows you to store key-value pairs, and then pass the dictionary a key to quickly retrieve its corresponding value. Specifically, you construct the dictionary by specifying one-way mappings from key-objects to value-objects.

What is key and value in dictionary in Python?

An item has a key and a corresponding value that is expressed as a pair (key: value). While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique.

How do you validate a key and value in a dictionary?

To check if a key-value pair exists in a dictionary, i.e., if a dictionary has/contains a pair, use the in operator and the items() method. Specify a tuple (key, value) . Use not in to check if a pair does not exist in a dictionary.


1 Answers

Yes it's always true. Guaranteed by Python iff there are no intervening modifications to the ditionary.

Relevant spec: http://docs.python.org/library/stdtypes.html#dict.items

This is better generally, both because it protects against the dict going out of sync and uses negligible extra memory:

dict((k,v) for k,v in d.iteritems())

like image 80
Kenan Banks Avatar answered Sep 18 '22 22:09

Kenan Banks