-1

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.

approximatenumber
  • 467
  • 1
  • 7
  • 22
  • Try using this https://stackoverflow.com/questions/40985281/python-comparing-values-in-the-same-dictionary or just try by availing the for loops and play with it would help you out. – Rahul shukla Oct 18 '19 at 07:32
  • If you have `pandas` installed: `[{k:v} for k,v in pd.DataFrame(components,dtype=float).max().to_dict().items()]`. – Henry Yik Oct 18 '19 at 07:50
  • @HenryYik thanks! But it has to be small builtin script without dependencies... – approximatenumber Oct 18 '19 at 07:53

2 Answers2

1

An example of achieving this might be:

components = [
    {"component1": "0.1"},
    {"component2": "0.2"},
    {"component1": "0.3"},
    {"component1": "0.2"},
    {"component2": "1.0"}
]
result = dict()
for d in components:
    for key, value in d.items():
        if key in result:
            if float(result[key])<float(value):
                result[key]=value
            else:
                continue
        else:
            result[key] = value
print(result)

the output for this is:

{'component1': '0.3', 'component2': '1.0'}
ymochurad
  • 941
  • 7
  • 15
1

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())}
splash58
  • 26,043
  • 3
  • 22
  • 34