2

So i have following dict:

my_dict{'key1': 'value1',
        'key2': 'value2',
        'key3': json.dumps([
           {"**subkey1**": "subvalue1", "**subkey2**": "subvalue2",},
           {"**subkey1**": "other_subvalue", "**subkey2**":"other_subvalue2"}])
       }

What I need is to somehow made a def where i have to check and for each subkey2 to change its value only for the def itself

And all subkey1 to check if its value is the same like the second subkey1 Please note I am talking about only subkey1 which I have twice.

I don't want to set them manually. Mean I have this dict global, and calling it from many def, so i need to make these changes and check inside each def

What I tried is:

def recurse_keys(my_dict, indent = ''):
    print(indent+str(key))
    if isinstance(my_dict[key], dict):
        recurse_keys(my_dict[key], indent+'   ')
recurse_keys(my_dict)

And for now it is only printing all of my params, but am not sure how to proceed

Example:

my_dict{'name': 'georgi',
        'famili': 'ivanov',
        'drinks': json.dumps([
           {"breakfast": "milk", "lunch": "beer",},
           {"breakfast": "tea",       "lunch":"vodka"}])
def test()
    ....check if both breakfast are the same and if not make them so....(all these, mean dict and the function it self are in same file)

so I need to check if the values for the two breakfast are the same (without to know them) and if they are not, to make them so.

And also to check if there is lunch with empty value or 0 and again if not, to make it so

George G.
  • 155
  • 1
  • 4
  • 13
  • Are you just trying to get it to print out a dictionary in a way that's nice and easy to ready? You mention changes - but your example function makes no changes - is this expected? – jimjkelly Jan 27 '16 at 12:04
  • yes it is not making changes because i don't know how to make them.... I need to make change of the second value, and to compare first value. But have no idea how to – George G. Jan 27 '16 at 13:02
  • If all you care about is making the values for the "breakfast" subkeys the same, then why not just assign both a value of "0", or "milk", or whatever? Why do you need to inspect the values if you aren't doing anything with them? – gariepy Jan 27 '16 at 14:41

1 Answers1

2

If you want to edit a json string, then probably the easiest way is to decode it to python data types d = json.loads(str), edit it, then encode it back to string str = json.dumps(d) (python JSON).

import json

my_dict = {'name': 'georgi',\
        'famili': 'ivanov',\
        'drinks': json.dumps([\
           {"breakfast": "milk", "lunch": "beer",},\
           {"breakfast": "tea", "lunch":"vodka"}])};

ddict = json.loads(my_dict["drinks"]) # json str to python data types

seen = {}; # store the items already seen

# for each dictionary object in key3
for d in range(0,len(ddict)):
    for k in ddict[d]:
        if k in seen:
            # update the value to the one already seen
            ddict[d][k] = seen[k];

        if k == "lunch" and (ddict[d] == "" or ddict[d] is None):
            ddict[d] = alternative_lunch_value;

        else:
            seen[k] = ddict[d][k];

my_dict["drinks"] = json.dumps(ddict);

print(my_dict);

The result on my machine is:

{'drinks': '[{"breakfast": "milk", "lunch": "beer"}, {"breakfast": "milk", "lunch": "beer"}]',
'famili': 'ivanov',
'name': 'georgi'}

Updating dict values

Because you wanted to update the values in my_dict so that it can be read by other modules, rather than just read the values. If all you wanted to do was read the values, then you can iterate over the list ddict as follows:

for value in ddict:
    print("Sub1:{0} Sub2:{1}\n".format(value["**subkey1**"], value["**subkey2**"]));

However, since you want to update the values in the existing list, then you will need to iterate over a list of the indexes. As shown below...

Range() and len()

Range(start,end) gives a list with values from start to end. So a = range(1,4) assigns [1,2,3,4] to a. Also len(a) will return the number of items in the list, so 4 in this case. Using these principals, you can iterate through your ddict.

for d in range(1,len(ddict):
    ddict[d]["**subkey1**"] = new_value;

Hope this helps get you started. If you update your question with more details on exactly what you want (i.e. example input and output, perhaps psudo code), then we will be able to give you a better answer.

James McCorrie
  • 2,283
  • 3
  • 18
  • 22
  • the point is that I actually don't know what is the value itself, so i need to match if they are the same only without to provide the value. I know the key only, so i need to match the values of subkey1 if they are the same And yes, I will have golbal dict that will be used from all 'def's and in some of these defs, i need to change the value of subkey2 for the need of the def – George G. Jan 27 '16 at 14:08
  • and: I need to match the two subkey1 that are with same name and dif values, not the subkey1 and subkey2. And if they are not with the same value, to make them to be. I've edited my post like u suggested, thank you! – George G. Jan 27 '16 at 14:15
  • Okay, I'm afraid I'm still struggling to understand your English. What do you mean by a 'def'? Do you mean your importing a module with a global variable and taking local copies which you want to then tweak the values of for local use? – James McCorrie Jan 27 '16 at 14:22
  • Just read your updated question. Thanks, that is a lot clearer. If you find different values, which value do you want to take as the actual value? The first value? – James McCorrie Jan 27 '16 at 14:26
  • Just edited it again, in same py file i want to make a function that checks them, the first one, actually it doesnt matter, it just have to be the same. Like for the lunch, it just have to become 0 or empty – George G. Jan 27 '16 at 14:27
  • How is that? I still didn't quite understand what you wanted to do with empty lunch values. But this should be more than enough to get you going. If your happy with this, please make it the accepted answer... – James McCorrie Jan 27 '16 at 14:38
  • for d in range(1,len(ddict): ^ SyntaxError: invalid syntax this is if i run the whole u wrote. If i try only: ddict = json.loads(my_dict["drinks"]) for d in range(1,len(ddict)): ddict[d]["breakfast"] = "20410"; it executes without errors, but no values are changed – George G. Jan 27 '16 at 14:47
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/101786/discussion-between-djmccorrie-and-george-g). – James McCorrie Jan 27 '16 at 14:50