Home > Software engineering >  Find a corresponding number from an array of strings in a long text file
Find a corresponding number from an array of strings in a long text file

Time:11-23

I have a text file that that has a single string formatted like this, each number nad name is unique:

{"5-6 digit number":"name", "5-6 digit number":"name", ..., "5-6 digit number":"name"}

I also have a Python array that contains 200 unique name strings and I want to iterate through this array to find the matching 5-6 digit number and store it as a tuple. The problem is im unsure of what is an appropriate method to do this since the single string in the text file has the "5-6 digit number":"name" bit 24,000 times. Would it be appropriate to read in the text file and store each element as an array and search through it or use something like SQL or maybe a different approach.

Here's an example to illustrate:

Text File:

{"774774":"John","775005":"Steve","35942":"Jacob", ...,"768252":"Matt"} (24,000 elements)

Python Array:

['Jacob', 'Janet', ...,'John'] (200 elements)

CodePudding user response:

It sounds like you need an inverse mapping of name to number. You can use a dict comprehension for this, and just flip the key: value syntax as below:

num_to_name = {"774774":"John","775005":"Steve","35942":"Jacob", "768252":"Matt"}

name_to_num = {v: k for k, v in num_to_name.items()}

print(name_to_num)
# {'John': '774774', 'Steve': '775005', 'Jacob': '35942', 'Matt': '768252'}

Once you have a mapping of name to number, you can simply use key lookup to find the 6-digit number for each name in a list of names:

array = ['Jacob', 'Janet', 'John']

for name in array:
    print(name, name_to_num.get(name, -1))  # where -1 when no number exists for name

Out:

Jacob 35942
Janet -1
John 774774
  • Related