Abruzzo Forte e Gentile
Abruzzo Forte e Gentile

Reputation: 14869

merging in python

I have the following 4 arrays ( grouped in 2 groups ) that I would like to merge in ascending order by the keys array.

I can use also dictionaries as structure if it is easier.

Has python any command or something to make this quickly possible?

Regards MN

# group 1
[7, 2, 3,  5]  #keys
[10,11,12,26]  #values 

[0,   4]   #keys
[20,  33]  #values 

# I would like to have
[ 0, 2, 3, 4, 5, 7 ] # ordered keys
[20, 11,12,33,26,33] # associated values

Upvotes: 1

Views: 150

Answers (4)

Dawie Strauss
Dawie Strauss

Reputation: 3706

If your keys are not guaranteed to be unique you should not use a dictionary - duplicate keys will be overwritten.

This solution works for duplicate keys:

keys_a = [7, 2, 3,  5]
values_a = [10,11,12,26]
keys_b = [0,   4]
values_b = [20,  33]

combined = zip(keys_a+keys_b, values_a+values_b)
combined.sort()

keys, values = zip(*combined)

(Edited to use @tgray's suggested improvement)

Upvotes: 3

MAK
MAK

Reputation: 26586

  1. Add all keys and associated values from both sets of data to a single dictionary.
  2. Get the items of the dictionary ans sort them.
  3. print out the answer.

    k1=[7, 2, 3, 5] v1=[10,11,12,26]

    k2=[0, 4] v2=[20, 33]

    d=dict(zip(k1,v1)) d.update(zip(k2,v2))

    answer=d.items() answer.sort() keys=[k for (k,v) in answer] values=[v for (k,v) in answer]

    print keys print values

Edit: This is for Python 2.6 or below which do not have any ordered dictionary.

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838176

I would recommend that you use dictionaries, then you can use d.update to update one dictionary with keys and values from the other.

Note that dictionaries in Python are not ordered. Instead when you need to iterate you can get their keys, order those and iterate over the keys in order getting the corresponding values.

If you are using Python 2.7, or 3.1 or better then there is a class OrderedDict that you might want to use.

Upvotes: 6

Sean Vieira
Sean Vieira

Reputation: 159905

Look at zip in combination with dictionary if your keys are guaranteed to be unique.

You just do:

>>> x = [7, 2, 3,  5]  #keys
>>> y = [10,11,12,26]  #values 

>>> dict(zip(x,y))
{2: 11, 3: 12, 5: 26, 7: 10}

Upvotes: 2

Related Questions