Skip to content

Instantly share code, notes, and snippets.

@a-toms
Last active February 13, 2024 13:04
Show Gist options
  • Save a-toms/a732ce010e1ef8b3cb0e908d8b6c3c69 to your computer and use it in GitHub Desktop.
Save a-toms/a732ce010e1ef8b3cb0e908d8b6c3c69 to your computer and use it in GitHub Desktop.
Convert a css string to python dictionary in a simple, robust manner
import tinycss2
from tinycss2.ast import WhitespaceToken
from tinycss2 import serialize
def css_to_dict(css: str) -> Dict[str, str]:
"""
Convert a CSS string to a dictionary of CSS attributes.
"""
return {
property.strip(): value.strip()
for property, value in (item.split(':') for item in css.split(';') if item)
}
css_string = '.nav-right { display: flex; border-top: 1.2px solid blue; color: #000000; width: 85.4%; }'
rules = tinycss2.parse_stylesheet(
css_string,
skip_comments=True,
skip_whitespace=True
)
css_dict = {}
for rule in rules:
selector = serialize(rule.prelude).strip()
declarations_str = serialize(rule.content).strip()
declarations_dict = services.css_to_dict(declarations_str
css_dict[selector] = declarations_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment