0

I have a long list of tuples of ions and wavelengths :

[('Cu II', 515.323),('Cu I', 515.809),('Cu VII', 518.336),...]

The first element in each tuple is an ion number, and I have made a list that grabs each type of ion that appears in the whole tuple list.

['Cu II','Cu I','Cu XV'...]

How do I create a new dictionary (or numpy array) that matches each wavelength to the affiliated ion number/type? I want it to look something like this (fake values used)

{'Cu I: 515.8,444,333..., 'Cu II':515.3,343,233, ...}
peasqueeze
  • 121
  • 2
  • 10
  • What is your question? – roganjosh Jan 30 '18 at 22:08
  • How does your question differ [from this](https://stackoverflow.com/a/6522469/8881141)? – Mr. T Jan 30 '18 at 22:12
  • @Piinthesky I believe the difference is that the dict values should be a list (or string the question is not clear) of all the matching key values. There is no doubt many applicable dupes on SO somewhere. – Paul Rooney Jan 30 '18 at 22:14
  • @PaulRooney But the list of ion types, according to the question, is made from the list of tuples. – Mr. T Jan 30 '18 at 22:16

2 Answers2

3

Try using a defaultdict:

from collections import defaultdict

d = defaultdict(list)
for item in tuples:
    d[item[0]].append(item[1])
fraczles
  • 81
  • 3
0

I think the most pythonic way to do this is a dictionary comprehension:

>>> big_list = [('Cu II', 515.323),('Cu I', 515.809),('Cu VII', 518.336)]
>>> wavelengths = { ion : wavelength for ion, wavelength in big_list}
>>> wavelengths['Cu II']
515.323
dax
  • 591
  • 2
  • 6
  • 16
  • This wouldn't be the most pythonic way because it doesn't work. It keeps re-defining a single value stored against the key. The OP clearly shows multiple values stored against a single key, this redefines the key:value pair. – roganjosh Jan 30 '18 at 22:19
  • Then I misunderstood the question. An ion can have multiple wavelengths? – dax Jan 30 '18 at 22:25
  • I'm not sure exactly what the basis of the OP's question is; I know they can absorb different wavelengths from HPLC-UV analysis but that's probably irrelevant. The point was to go off the OP's intended output: `{'Cu I: 515.8,444,333..., 'Cu II':515.3,343,233, ...}` – roganjosh Jan 30 '18 at 22:28