Skip to content
Advertisement

How to compare components versions and find the latest ones in python list of dict?

I have a simple list of components dict to install.

components = [
    {"component1": "0.1"},
    {"component2": "0.2"},
    {"component1": "0.3"},
    {"component1": "0.2"},
    {"component2": "1.0"}
]

Components may be the same, but have different versions. I want to get a list of components with latest versions. So, expecting result is

latest_components = [
    {"component1": "0.3"},
    {"component2": "1.0"}
]

What is the best way to compare component to each other? I tried to solve it using bash, but it looks like crap, so I want to make it more readable using python.

Advertisement

Answer

One line. Works with multilevel versions (1.2.4.7…)

{c:'.'.join(map(str,v)) for c,v in sorted([c,list(map(int, v.split('.')))] for l in components for c,v in l.items())}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement