pranphy
pranphy

Reputation: 1889

Insert dictionary in a list of dictionaries in order

I have a list

 [{'FloatVal':Floatm,'StrVal':'Strm'},{'FloatVal':Floatn,'StrVal':'Strn'}...]

The sequence are ascending order Floatm < Floatn < ... I want to insert a dictionary {'FloatVal':FloatX,'StrVal':'StrX'} in the list making the Floatx in order. If Floatm<FloatX<Floatn then I want the final list to be

 [{'FloatVal':Floatm,'StrVal':'Strm'},{'FloatVal':FloatX,'StrVal':'StrX'},{'FloatVal':Floatn,'StrVal':'Strn'}...]

What would be the best pythonic way to do it?

Upvotes: 0

Views: 64

Answers (2)

fjarri
fjarri

Reputation: 9726

You can use the bisect module, or an existing implementation of the sorted list that uses this module. With the latter:

s = SortedCollection([{'FloatVal':1}, {'FloatVal':2}], key=lambda x: x['FloatVal'])
s.insert({'FloatVal': 1.5})
print(list(s))

[{'FloatVal': 1}, {'FloatVal': 1.5}, {'FloatVal': 2}]

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49318

Just sort it again, with a suitable key. Python uses a stable sort that is fast for nearly-sorted objects.

>>> result =  [{'FloatVal':'Floatm','StrVal':'Strm'},{'FloatVal':'Floatnb','StrVal':'Strnb'}]
>>> result.append({'FloatVal':'Floatna','StrVal':'Strna'})
>>> result
[{'FloatVal': 'Floatm', 'StrVal': 'Strm'}, {'FloatVal': 'Floatnb', 'StrVal': 'Strnb'}, {'FloatVal': 'Floatna', 'StrVal':'Strna'}]
>>> result.sort(key=lambda x: x['FloatVal'])
>>> result
[{'FloatVal': 'Floatm', 'StrVal': 'Strm'}, {'FloatVal': 'Floatna', 'StrVal': 'Strna'}, {'FloatVal': 'Floatnb', 'StrVal':'Strnb'}]

Upvotes: 4

Related Questions