I want to convert a dictionary into a list of strings. Although my actual code is much longer, a MWE is:
>>> import json
>>> mydict = {'c1': (84/255, 0/255, 0/255), 'c2': (15/255, 123/255, 175/255)}
>>> json.dumps(mydict)
The output is:
'{"c1": [0.32941176470588235, 0.0, 0.0], "c2": [0.058823529411764705, 0.4823529411764706, 0.6862745098039216]}'
If I try the fractions
package, it seems I can convert fractions themselves into something suitable but it doesn't work for dictionaries or arrays:
from fractions import Fraction
x = Fraction(84/255).limit_denominator()
print(x)
y = Fraction(np.array([84/255, 0/255])).limit_denominator()
print(y)
z = Fraction(mydict).limit_denominator()
print(z)
I want to extract all the numerical values (while keeping them as fractions) and put them in a list, something like:
mylist = ['(84/255, 0/255, 0/255)', '(15/255, 123/255, 175/255)']
FYI I can't save the tuples as strings in my actual code (not this MWE) because I'm not allowed to change the particular format. So it's necessary to convert mydict
directly, eg. like str(Fraction({'c1': (84/255, 0/255, 0/255), 'c2': (15/255, 123/255, 175/255)}).limit_denominator()
.