1

I have a dictionary of chemical symbols and names, to look up the symbol and get the name is easy, but to find the symbol of a given chemical name seems to be more akward. Am I missing something here?

# small dictionary of chemical symbols
symbol_dic = {
'C': 'carbon',
'H': 'hydrogen',
'N': 'nitrogen',
'Li': 'lithium',
'Be': 'beryllium',
'B': 'boron'
}

# show the name of a symbol
symbol = 'N'
print symbol_dic[symbol]  # nitrogen
Votes + Comments
great question
5
Contributors
4
Replies
8
Views
9 Years
Discussion Span
Last Post by jrcagle
1

There is no simple dictionary function build in, since values may not be unique, but you can use this:

# search a dictionary for key or value

def find_key(dic, val):
    """return the key of dictionary dic given the value"""
    return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
    """return the value of dictionary dic associated with a given key"""
    return dic[key]

# test it out
if __name__ == '__main__':
    # dictionary of chemical symbols
    symbol_dic = {
    'C': 'carbon',
    'H': 'hydrogen',
    'N': 'nitrogen',
    'Li': 'lithium',
    'Be': 'beryllium',
    'B': 'boron'
    }

    print find_key(symbol_dic, 'boron')  # B
    print find_value(symbol_dic, 'B')    # boron

I used functions for both searches naming them so it's easier to read.

Votes + Comments
nice clean code
0

In your case values are also unique, so you could swap the dictionary from symbol:name pairs to name:symbol pairs and then look up the name key ...

def swap_dic(dic):
    """swap dictionary key:value pairs with a generator expression"""
    return dict((v, k) for (k, v) in dic.items())

# dictionary of chemical symbols
symbol_dic = {
'C': 'carbon',
'H': 'hydrogen',
'N': 'nitrogen',
'Li': 'lithium',
'Be': 'beryllium',
'B': 'boron'
}

# swap the dictionary so the chemical name is the key
name_dic = swap_dic(symbol_dic)

print name_dic['hydrogen']  # H
print name_dic['lithium']   # Li
1

Or put them both in the same dictionary. There is only 100 or so-times 2

# small dictionary of chemical symbols
symbol_dic = {
'C': 'carbon',
'H': 'hydrogen',
'N': 'nitrogen',
'Li': 'lithium',
'Be': 'beryllium',
'B': 'boron'
}

keys_list=symbol_dic.keys()
for key in keys_list:
   symbol_dic[symbol_dic[key]]=key
Votes + Comments
very nice idea
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.