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
Ene Uran commented: great question +4

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.

commented: nice clean code +1

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

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
commented: very nice idea +4

Hey -- nice idea, wooee.

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.