问题描述
所以我有以下格言:
my_dict{'key1': 'value1',
'key2': 'value2',
'key3': json.dumps([
{"**subkey1**": "subvalue1", "**subkey2**": "subvalue2",},
{"**subkey1**": "other_subvalue", "**subkey2**":"other_subvalue2"}])
}
我需要以某种方式创建一个def,我必须在其中检查并且每个subkey2仅针对def本身更改其值
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
和所有subkey1一起检查其值是否与第二个subkey1相同请注意,我只说说我有两次的subkey1.
And all subkey1 to check if its value is the same like the second subkey1Please note I am talking about only subkey1 which I have twice.
我不想手动设置它们.意味着我有这个全局的dict,并从许多def调用它,所以我需要进行这些更改并检查每个def的内部
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
我尝试过的是:
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
示例:
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.
还要检查午餐是否为空值或是否为0,否则为空.
And also to check if there is lunch with empty value or 0 and again if not, to make it so
推荐答案
如果要编辑json字符串,则可能最简单的方法是将其解码为python数据类型d = json.loads(str)
,对其进行编辑,然后将其编码回来字符串str = json.dumps(d)
( Python JSON ).
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);
我的机器上的结果是:
{'drinks': '[{"breakfast": "milk", "lunch": "beer"}, {"breakfast": "milk", "lunch": "beer"}]',
'famili': 'ivanov',
'name': 'georgi'}
更新字典值
因为要更新my_dict
中的值,以便其他模块可以读取它,而不仅仅是读取值.如果您只想读取值,则可以遍历列表ddict
,如下所示:
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(start,end)给出一个从开始到结束的值列表.因此,a = range(1,4)
将[1,2,3,4]
分配给a
.同样,len(a)
将返回列表中的项目数,因此在这种情况下,4
.使用这些原理,您可以遍历ddict
.
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.
这篇关于在python中更改json.dumps字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!