School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 307,136 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,864 people online right now. Registration is fast and FREE... Join Now!




Preserve Dictionary Order

 

Preserve Dictionary Order, How do I keep the order of my dictionary

reyno2ac

4 Oct, 2009 - 07:41 PM
Post #1

New D.I.C Head
*

Joined: 10 Sep, 2009
Posts: 4


My Contributions
I'm extremely new to python, so please go easy on me.

I'm trying to take the values from two dictionaries and compute their sums. For example:
A = {1:4, 5:2, 6:3, 8:7}
B = {2:1, 4:4, 7:5, 9:2}
The result should be [5, 9, 6, 8].

For some reason the program is outputting [9, 5, 6, 8].

CODE

def sparse_add():
    A = {1:4, 5:2, 6:3, 8:7}
    B = {2:1, 4:4, 7:5, 9:2}
    i = 0
    ab_total = {}
    a_list = []
    b_list = []
    
    #converts A and B to lists
    a_list = A.values()
    b_list = B.values()
    
    #adds A and B to ab_total
    if len(a_list) == len(b_list):
        while i < len(a_list):
            ab_total[i] = a_list[i] + b_list[i]
            i = i+1
    else:
        print "Your vectors do not contain an even amount of elements"

    print "The new dictionary is:", ab_total
    print "The sum of the dictionaries is:", ab_total.values()
    #should print 5, 6, 8, 9

if __name__ == '__main__':
    sparse_add()
blink.gif

User is offlineProfile CardPM
+Quote Post


Nallo

RE: Preserve Dictionary Order

5 Oct, 2009 - 03:21 AM
Post #2

New D.I.C Head
*

Joined: 19 Jul, 2009
Posts: 24



Thanked: 3 times
My Contributions
The order of the items (key, value pairs) in dictionaries is not preserved.

So if you need the values in a certain order there are serveral ways:

1. Dont put them in a dictionary in the first place, use a list or a tuple
2. If your keys are ordered you can iterate over the keys (after you sorted them) insted of values:
CODE
def add(dic1, dic2):
    key1, key2 = dic1.keys(), dic2.keys()

    #now lets get back the order
    key1.sort()
    key2.sort()
    

    total = []
    for i, j in zip(key1, key2):
        #total is a list here, I dont see reason to make it a dict
        total.append(dic1[key1] + dic2[key2])

    return total

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/21/09 03:04PM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month