473,696 Members | 1,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Order of elements in a dict

Hi!

In dictionaries, unlinke lists, it doesn't matter the order one inserts
the contents, elements are stored using its own rules.

Ex:
d = {3: 4, 1: 2}
d {1: 2, 3: 4}

So, my question is: if I use keys() and values() it will give me the
keys and values in the same order?

In other words, it is safe to do:
dd = dict(zip(d.valu es(),d.keys()))
to exchange keys and values on a dictionary? Or I can have the values
and keys in a different order and end with something like this:
dd {2: 3 , 4: 1}

instead of:
dd

{2: 1, 4: 3}

For this example it works as I wanted (the second output), but can I
trust this?

Also, if someone has a better way to exchange keys and values in a dict,
I would like to learn. :-)

Thanks!

Marcio
Jul 19 '05 #1
7 3096
Marcio Rosa da Silva wrote:
In other words, it is safe to do:
>>> dd = dict(zip(d.valu es(),d.keys()))


Yes, if the dictionary isn't modified between the invocation of values() and
keys(). Quoting http://docs.python.org/lib/typesmapping.html

"""
Keys and values are listed in an arbitrary order which is non-random, varies
across Python implementations , and depends on the dictionary's history of
insertions and deletions. If items(), keys(), values(), iteritems(),
iterkeys(), and itervalues() are called with no intervening modifications
to the dictionary, the lists will directly correspond. This allows the
creation of (value, key) pairs using zip(): "pairs = zip(a.values(),
a.keys())". The same relationship holds for the iterkeys() and itervalues()
methods: "pairs = zip(a.itervalue s(), a.iterkeys())" provides the same
value for
"""

I suppose you are aware that you lose information if multiple keys have the
same value.

Peter
Jul 19 '05 #2
Marcio Rosa da Silva wrote:
In other words, it is safe to do:
dd = dict(zip(d.valu es(),d.keys()))

to exchange keys and values on a dictionary?


See the Library Reference, section 2.3.8 Mapping Types:
Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations , and depends on the dictionary's
history of insertions and deletions. If items(), keys(), values(),
iteritems(), iterkeys(), and itervalues() are called with no
intervening modifications to the dictionary, the lists will directly
correspond. This allows the creation of (value, key) pairs using
zip(): "pairs = zip(a.values(), a.keys())". The same relationship
holds for the iterkeys() and itervalues() methods: "pairs =
zip(a.itervalue s(), a.iterkeys())" provides the same value for pairs.
Another way to create the same list is "pairs = [(v, k) for (k, v) in
a.iteritems()]".

Jul 19 '05 #3
Marcio Rosa da Silva wrote:
In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are
stored using its own rules.

Ex:
d = {3: 4, 1: 2}
d

{1: 2, 3: 4}

So, my question is: if I use keys() and values() it will give me the keys and values in the same
order?


http://docs.python.org/lib/typesmapping.html

"Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations , and depends on the dictionary's
history of insertions and deletions. If items(), keys(), values(), iteritems(),
iterkeys(), and itervalues() are called with no intervening modifications
to the dictionary, the lists will directly correspond."

</F>

Jul 19 '05 #4
Thanks for the help!

Marcio
Jul 19 '05 #5
Marcio Rosa da Silva wrote:
So, my question is: if I use keys() and values() it will give me the
keys and values in the same order?
It should work fine with the current implementation of dictionaries, but
(AFAIK) it's not guaranteed to work by the mapping protocol. So
theoretically, it could break under Python 2.5 or with a user-made
mapping type.
Also, if someone has a better way to exchange keys and values in a dict,
I would like to learn. :-)


I would do it like this:
d = {1: 2, 2: 3, 3: 4}
d = dict([(value, key) for key, value in d.iteritems()])
d

{2: 1, 3: 2, 4: 3}
Jul 19 '05 #6
Here is a brute-force list comprehension that does not depend on
preserving order between dict.keys() and dict.values():

dict( [ (a[1],a[0]) for a in d.items() ] )

Or for map/lambda lovers:

rev = lambda a: (a[1],a[0])
dict( map( rev, d.items() )

But you still have no control over the order returned by d.items(), so
if your initial dict has duplicate values, there is no telling which
key a duplicate would map to.

The real general-purpose dict inversion results in a dict with each
value containing a list of keys in the original dict that mapped to the
given value. That is:
d = {3: 4, 1: 2, 0:4}
would invert to:
d2 = { 2:[1], 4:[0,3] }

I couldn't cram this into a list comp, so here is a short for loop to
create d2:
d2 = {}
for k,v in d.items():
d2[v] = d2.get(v, list()) + [k]

-- Paul

Jul 19 '05 #7
Marcio Rosa da Silva wrote:
Hi!

In dictionaries, unlinke lists, it doesn't matter the order one inserts
the contents, elements are stored using its own rules.

Ex:
>>> d = {3: 4, 1: 2}
>>> d {1: 2, 3: 4}

So, my question is: if I use keys() and values() it will give me the
keys and values in the same order?

In other words, it is safe to do:
>>> dd = dict(zip(d.valu es(),d.keys()))
to exchange keys and values on a dictionary? Or I can have the values
and keys in a different order and end with something like this:
>>> dd {2: 3 , 4: 1}

instead of:
>>> dd

{2: 1, 4: 3}

For this example it works as I wanted (the second output), but can I
trust this?

Also, if someone has a better way to exchange keys and values in a dict,
I would like to learn. :-)

Thanks!

Marcio


Well, a footnote to the "Mapping types" page in the Library Reference says

"""Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations , and depends on the dictionary's
history of insertions and deletions. If items(), keys(), values(),
iteritems(), iterkeys(), and itervalues() are called with no intervening
modifications to the dictionary, the lists will directly correspond.
This allows the creation of (value, key) pairs using zip(): "pairs =
zip(a.values(), a.keys())". The same relationship holds for the
iterkeys() and itervalues() methods: "pairs = zip(a.itervalue s(),
a.iterkeys())" provides the same value for pairs. Another way to create
the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]". """

So it looks as though you will be safe, since there's a promise in the
documentation.

If you just want to iterate over the (key, value) pairs, however, you
should normally choose items() or iteritems() to do so. Then you could
use (for example):

dd = dict((x[1], x[0]) for x in d.items())

I presume you are confident that each value will only occur once in the
original dictionary, as otherwise the result will be smaller than the input.

regards
Steve
--
Steve Holden +1 703 861 4237 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/

Jul 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7063
by: Brainwashed | last post by:
Is there any order in dictionaries that will never change ? I've noticed that assigning always the same elements to the dict puts them always in the same order. Like regexp which takes 3 values, 'year', 'month', 'day' - I always get this order: 'year': .., 'day':.., 'month':.. No idea why this order tho.. :) Is there any philosophy in this ? And if I add only one new value to this regexp, so that it takes 4 now the order changes...
1
1991
by: svilen | last post by:
hi. this was named but it is misleading. i want to have the order of setting items in intrinsic dicts (keyword args, or class attributes, etc). which is, a prdered dict trhat matches the source-text sequences.
7
3660
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc. And i have things to offer, and to request. And a lot of ideas, but who needs them.... here's an example (from type_struct.py):
39
2917
by: Nicolas Fleury | last post by:
In the following example: class MyMetaclass(type): pass class MyBaseType(object): __metaclass__ = MyMetaclass class MyType(MyBaseType): x = 4 y = 5 z = 6 Is there any way to modify MyMetaclass to keep the order of x,y,z somewhere?
12
2008
by: Christopher J. Bottaro | last post by:
If I have the following class: class MyClass: def __init__(self): m_dict = {} m_dict = 1 m_dict = 2 m_dict = 3 Is there anyway to generate automatic accessors to the elements of the dict?
3
1475
by: bonono | last post by:
Hi, I am wondering if there is a dictionary data type that allows me to define the order of access when iterating it using items/keys etc. ? An example: a=dict(a=dict(), c=dict(), h=dict()) prefer=
6
5509
by: Kamilche | last post by:
I have a code snippet here that prints a dict in an arbitrary order. (Certain keys first, with rest appearing in sorted order). I didn't want to subclass dict, that's error-prone, and overkill for my needs. I just need something that returns a value like dict.__str__, with a key ordering I specify. If you have any opinions on how it could be made better, I'm all ears!
8
7921
by: spohle | last post by:
hi i have a normal dictionary with key and value pairs. now i wanna sort by the keys BUT in a specific order i determine in a list !? any ideas dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} list =
7
2518
by: psbasha | last post by:
Hi, In case of the 'dict',the stored elements will not be in a order.It will be randomly arranged ( not as list,in list the elements will be arranged in order as we store it). For Example : --------------------- Input : Elements stored in order >>> d = {1:,100:,2:} output ( Not as expected): Order of the dict Elements as we stored has been changed >>> d
0
9145
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9010
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8880
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8853
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5857
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4356
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3033
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2319
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.