Python Forum

Full Version: updating certain values in dict. with relation to their keys
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(Nov-27-2019, 10:23 AM)malevy Wrote: [ -> ]the keys are not ordered or following/
more spam like mess Wink **
not sure I understand. The order of the key is irrelevant. Ignore that they are sorted in my example. You didn't show sample data, so I had to invent
As to the order - as of python 3.7. dicts are order-preserving. i.e. the order in which keys are inserted/created in the dict is preserved. Before that they were unordered collection.
what u did is amazing
im still trying to figure out the python code qoute thing :)
the full picture is still not clear - e.g. would you repeat the process in which case different approach may be better, etc.
Hi malevy, this is how i understand what you want to do. Is that right?
dictionary = {1: 10, 2: 20, 3: 30, 4:40}

current = 10
found = False

for key, value in dictionary.items():
    if value == current:
        dictionary[key] = value + 3 * key
        found = True

if not found:
    dictionary[current] = current * 2
yesss!
thank you man
you solved it
genious
spam = {1:3, 4:6, 7:6, 9:10}
current = 6
 
if current in spam.values():
    for key, value in spam.items():
        if value = current:
            spam[key] = value + 3 * key
else:
    spam[current] = current * 2
@buran with regards to runtime considerations your solution is not optimal.
Searching through spam.values() is slower than through a normal list
In worst case, if value is last item in spam.values() you iterate twice over all items in dictionary.
Using my code you iterate only once even in worst case.
@ThomasL, you are right. I didn't look at it from optimisation perspective
Pages: 1 2