Vijay
Vijay

Reputation: 27

value is not updating into dict

I need to compare values from two dict1 and dict2 and i need to update new value in dict1.

Below are the code

dict2 = {'partname1': {'jarversion': '1.0', 'jarname': 'jar1.jar'},
         'partname2': {'jarversion': '2.0', 'jarname': 'jar2.jar'},
         'partname3': {'jarversion': '3.0', 'jarname': 'jar3.jar'}}

dict1 = {1: {'partition_name': 'avs',
             'jar': [{'jarversion': '1.0', 'jarname': 'jar1.jar'}, {'jarversion': '5.0', 'jarname': 'jar5.jar'}]},
         2: {'partition_name': 'ivs',
             'jar': [{'jarversion': '4.0', 'jarname': 'jar4.jar'}, {'jarversion': '2.0', 'jarname': 'jar2.jar'}], }}

code i am using below.

res = []
for _, v in dict2.items():
    res.append(v['jarname'] + v['jarversion'])

def cmp_value(rstring='', lstring=''):
    print('rstring', rstring)
    print('lstring', lstring)
    if rstring == lstring:
        print("true.......................................")
        return True
    else:
        return False


for key, val in dict1.items():
    print(val)
    for eachval in res:
        for i in val['jar']:
            if cmp_value(eachval, "%s%s" % (i['jarname'], i['jarversion'])):
                i['overwrite'] = 'true'

            else:
                i['overwrite'] = 'false'


print(dict1)

The results is

{1: {'partition_name': 'avs', 'jar': [{'jarversion': '1.0', 'jarname': 'jar1.jar', 'overwrite': 'false'}, {'jarversion': '5.0', 'jarname': 'jar5.jar', 'overwrite': 'false'}]}, 2: {'partition_name': 'ivs', 'jar': [{'jarversion': '4.0', 'jarname': 'jar4.jar', 'overwrite': 'false'}, {'jarversion': '2.0', 'jarname': 'jar2.jar', 'overwrite': 'false'}]}}

As you see above all the "overwrite" value showing "false". I am using pretty old python version 2.2.1 So ( sets and comprehension) wont work here. So with the above i can add any code

Upvotes: 0

Views: 34

Answers (1)

Dima G
Dima G

Reputation: 2025

This is an algorithmic bug. Your final value of the overwrite is set based on the last comparison. It means that you would want to stop iterating over res once cmp_value(...) returns true.

You can try to swap the loops hierarchy and break the loop on true:

...
for i in val['jar']:
    for eachval in res:
        if cmp_value(eachval, "%s%s" % (i['jarname'], i['jarversion'])):
            i['overwrite'] = 'true'
            break
        else:
            i['overwrite'] = 'false'
     

Upvotes: 1

Related Questions