Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forming a chemical formula from a string of elements python

I want to ask a question about converting a list of items into a string.

I have the following list of a SiH2O molecule, where the 2 implies the subscript of 2 hydrogen atoms:

[['Si', array([0, 1, 2])], 
['H', array([3, 4, 5])], 
['O', array([6, 7, 8])],
['H', array([3, 4, 5])]]

My intention is to convert this data into a chemical formulae i.e. SiH2O.

Another example is shown below:

['H', array([3, 4, 5])], 
['F', array([6, 7, 8])],
['H', array([3, 4, 5])]]

I am attempting to convert this to H2F (without any subscript formatting - I purely want to reach the H2F output.)

My attempt so far is as follows:

I first looped through the string to retrieve all the chemical symbols:

symbols = []
for item in string:
    symbols.append(item[0])
symbols

I then tried to find the unique atoms in the string (i.e. a string of elements that are only repeated once in the string):

unique = []
for i in symbols:
    if i not in unique:
        unique.append(i)

And this returned

['Si', 'H', 'O']

and

['H', 'F'] 

respectively.

I attempted to create a dictionary of the elements and their count, with an original default of 0:

myDict = {key:0 for key in unique}

and then attempted to count through the dictionary.

for item in symbols:
    count = myDict[item]
    count += 1
    myDict[item] = count

This returns:

{'Si': 1, 'H': 2, 'O': 1}

Now, I want to use the key, value pair to compile the string SiH2O. I used the condition if value == 1 then I would not attach the subscript number after the chemical symbol.

This was the code I attempted.

chemical_string = ""
for key, value in symbols:
    if value == 0:
        chemical_string += key
    else:
        chemical_string += key + "" + value

I expected the result SiH2O but I fall into this error:

ValueError                                Traceback (most recent call last)
<ipython-input-57-d5312c683c2e> in <module>
      1 chemical_string = ""
----> 2 for key, value in myDict:
      3     if value == 0:
      4         chemical_string += key
      5     else:

ValueError: not enough values to unpack (expected 2, got 1)

I'm confused on why this doesn't work. How can I solve this matter?

like image 731
vik1245 Avatar asked Jun 12 '26 19:06

vik1245


1 Answers

As per @Luka Mensaric's answer, I need to use the .items() method.

I also realised I need to convert value into a str inside the else statement:

chemical_string = ""
for key, value in myDict.items():
    if value == 1:
        chemical_string += key
    else:
        chemical_string += key + "" + str(value)
like image 124
vik1245 Avatar answered Jun 17 '26 04:06

vik1245



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!