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.

6 Answers 6

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))
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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]

Comments

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.

Comments

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]

Comments

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']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.