1

I have two Arrays:

firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]

So I just need an Array which is like

thirdArray=[[1,'AF'],[3,'AS']]

I tried any(e[1] == firstArray[i][1] for e in secondArray) It returned me True and false if second element of both array matches. but i don't know how to build the third array.

Steve Konves
  • 2,598
  • 3
  • 24
  • 44
saun jean
  • 707
  • 2
  • 11
  • 25

6 Answers6

6

First, convert firstArray into a dict with the country as the key and abbreviation as the value, then just look up the abbreviation for each country in secondArray using a list comprehension:

abbrevDict = {country: abbrev for abbrev, country in firstArray}
thirdArray = [[key, abbrevDict[country]] for key, country in secondArray]

If you are on a Python version without dict comprehensions (2.6 and below) you can use the following to create abbrevDict:

abbrevDict = dict((country, abbrev) for abbrev, country in firstArray)

Or the more concise but less readable:

abbrevDict = dict(map(reversed, firstArray))
Andrew Clark
  • 192,132
  • 30
  • 260
  • 294
2

It is better to store them into dictionaries:

firstDictionary = {key:value for value, key in firstArray}
# in older versions of Python:
# firstDictionary = dict((key, value) for value, key in firstArray)

then you could get the 3rd array simply by dictionary look-up:

thirdArray = [[value, firstDictionary[key]] for value, key in secondArray]
kennytm
  • 491,404
  • 99
  • 1,053
  • 989
2

You could use an interim dict as a lookup:

firstArray=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]
secondArray=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]

lookup = {snd:fst for fst, snd in firstArray}
thirdArray = [[n, lookup[name]] for n, name in secondArray]
Jon Clements
  • 132,101
  • 31
  • 237
  • 267
0

If a dictionary would do, there is a special purpose Counter dictionary for exactly this use case.

>>> from collections import Counter
>>> Counter(firstArray + secondArray)
Counter({['AF','AFGHANISTAN']: 1 ... })

Note that the arguments are reversed from what you requested, but that's easily remedied.

Johanna Larsson
  • 10,021
  • 6
  • 35
  • 49
0

use a list comprehension:

In [119]: fa=[['AF','AFGHANISTAN'],['AL','ALBANIA'],['DZ','ALGERIA'],['AS','AMERICAN SAMOA']]

In [120]: sa=[[1,'AFGHANISTAN'],[3,'AMERICAN SAMOA']]

In [121]: [[y[0],x[0]] for x in fa for y in sa if y[1]==x[1]]

Out[121]: [[1, 'AF'], [3, 'AS']]
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
0

The standard way to match data to a key is a dictionary. You can convert firstArray to a dictionary using dict comprehension.

firstDict = {x: y for (y, x) in firstArray}

You can then iterate over your second array using list comprehension.

[[i[0], firstDict[i[1]]] for i in secondArray]
kreativitea
  • 1,721
  • 12
  • 14