Noah Dukehart
Noah Dukehart

Reputation: 67

searching through a nested list python

I have written a code that searches through a web site and returns a nested list of currency values and exchange rates a sample of the output is below

[['Argentine Peso', ['9.44195', '0.10591']], ['Australian Dollar', ['1.41824', '0.70510']], ['Bahraini Dinar', ['0.37743', '2.64953']]...

i need to write a code that takes the input of a name and returns the values associated with it so if i were to type in Argentine Peso it would return

[9.44195, 0.10591]

but im not really sure how to search through the list

Upvotes: 2

Views: 106

Answers (3)

Boa
Boa

Reputation: 2677

A variant that doesn't use list comprehensions or dicts:

currency_list = [['Argentine Peso', ['9.44195', '0.10591']], 
    ['Australian Dollar', ['1.41824', '0.70510']], 
    ['Bahraini Dinar', ['0.37743', '2.64953']]]

def search_list(query_string, cur_list):
    for key, val in cur_list:
        if key == query_string:
            return val

search_list('Australian Dollar', currency_list)

Each entry in your list is a list of two components:

  1. a string indicating a currency (key)
  2. a list indicating the currency's value range (value)

In python, you can automatically assign the values of a list of n values to n variables:

a, b, c = [7,8,9] 

That's analogous to how the (key, value) pair is generated at each iteration of the for loop.

However, using a solution which converts the list to a dict will give you the data structure which will perform the fastest lookups.

Upvotes: 0

metaperture
metaperture

Reputation: 2463

You probably want a dictionary instead of a list:

>>> l = [['Argentine Peso', ['9.44195', '0.10591']], ['Australian Dollar', ['1.41824', '0.70510']], ['Bahraini Dinar', ['0.37743', '2.64953']]]
>>> d = dict(l)
>>> d["Argentine Peso"]
['9.44195', '0.10591']

If, for some reason, you must use a list, I use something like the following sometimes:

>>> matches = [it for it in l if it[0] == query]
>>> assert len(matches) == 1, "match not found or ambiguous"
>>> matches[0]

...though I mostly use it for fuzzy matching. For exact matching, I'd highly recommend dictionaries; that's what they're there for.

Upvotes: 6

Steve Zelaznik
Steve Zelaznik

Reputation: 616

It's a one liner:

lookup = dict([['Argentine Peso', ['9.44195', '0.10591']], ['Australian Dollar', ['1.41824', '0.70510']], ['Bahraini Dinar', ['0.37743', '2.64953']]])

Upvotes: 0

Related Questions