Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting nested dict into a single unchanging unique number

I’m working on a minimax algorithm project and I am trying to find a way to save board values in a text file so they don’t need to be calculated over and over again each time the program is tested. I have the board stored as a nested dictionary.

rows = {
    4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    }

I tried doing this, which gives the desired result but is not at all optimized and I’m sure there is a way to do this better.

 rows = {
    4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    }

e = []
for key in rows:
    e.append(list(rows[key].values()))
e=str(e)
e=e.replace ("[",""); e=e.replace ("]","")
e=e.replace (" ","")
e=e.replace (",","")
print(e)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could make use of a str.join(), map is used to convert integers to strings:

res = ''.join(''.join(map(str, r.values())) for r in rows.values())
print(res)

Out:

00000000000000000000000000000000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading