Dict to JSON:
dict türünden tanımlanan a datasını json türünden b datasına çevirelim:
>>>import json
>>>a = {'name':'ali', 'no':21}
>>>a
{'name':'ali', 'no':21}
>>>type(a)
<class 'dict'>
>>>b = json.dumps(a)
>>>b
'{"name":"ali", "no":21}'
>>>type(b)
<class 'str'>
görüldüğü gibi json datası string yapıda ve içindeki string türünden değişken/veri çiftleri çift tırnak içindedir.Burası önemlidir,aksi halde json.dumps işleminde hata verir.
JSON to Dict:
json türünden tanımlanan a datasını dict türünden b datasına çevirelim:
>>>import json
>>>a = '{"name":"ali", "no":21}'
>>>a
'{"name":"ali", "no":21}'
>>>type(a)
<class 'str'>
>>>b = json.loads(a)
>>>b
{'name':'ali', 'no':21}
>>>type(b)
<class 'dict'>
örnek: {'code':20, 'name':'bob'} dict türünden verinin elemanlarını bulun:
a = {'code':20, 'name':'bob'}
for value in a.items():
s1=value[0]
s2=value[1]
print(s1,s2)
çıktısı:
-------
name bob
code 20
örnek: {'717': [0, 4], '250': [1, 5], '21': [3, 3], '1465': [2, 9], '695': [1, 7], '1202': [1, 1], '187': [1, 1], '280': [1, 1], '9': [8, 8]} dict türünden veriyi elemanlarına ayırınız.
a = {'717': [0, 4], '250': [1, 5], '21': [3, 3], '1465': [2, 9], '695': [1, 7], '1202': [1, 1], '187': [1, 1], '280': [1, 1], '9': [8, 8]}
for key, value in a.items():
s1=key
s2=value[0]
s3=value[1]
print(s1,s2,s3)
çıktısı:
-------
250 1 5
280 1 1
1465 2 9
9 8 8
695 1 7
187 1 1
1202 1 1
21 3 3
717 0 4
ÖRNEK:Dict türünden bir verinin değerlerini değiştirelim.Bu örnekte değeri "AAA" olan öğeyi güncelleyelim:
root = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}
dic = root['records'][0]
for i, j in dic.items():
if j == 'AAA':
dic[i] = 'xxx'
print(root)
sonuc:
{'records': [{'key3': 'CCC', 'key4': 'xxx', 'key2': 'BBB', 'key1': 'xxx'}]}
ÖRNEK:Dict türünden bir verinin değerlerini değiştirelim.Bu örnekte "key1" öğesinin değerini güncelleyelim:
root = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}
dic = root['records'][0]
for i, j in dic.items():
if i == 'key1':
dic[i] = 'a00'
print(root)
sonuc:
{'records': [{'key4': 'AAA', 'key2': 'BBB', 'key3': 'CCC', 'key1': 'a00'}]}
i-->öğe , j--->değer içerir.
ÖRNEK:Birden fazla sözlük öğesi içeren veriyi güncelleyelim:
root = {"records": [{"key1": "A01", "key2": "B01", "key3": "C01", "key4": "D01"}, {"key1": "A02", "key2": "B02", "key3": "C02", "key4": "D02"}, {"key1": "A03", "key2": "B03", "key3": "C03", "key4": "D03"}]} for dic in root['records']: for i, j in dic.items(): key3 = dic['key3'] #eğer key3 değerini almak istersek
if i == 'key1': dic[i] = 'a00' print(root)
sonuc:
{'records': [{'key4': 'D01', 'key3': 'C01', 'key2': 'B01', 'key1': 'a00'}, {'key4': 'D02', 'key3': 'C02', 'key2': 'B02', 'key1': 'a00'}, {'key4': 'D03', 'key3': 'C03', 'key2': 'B03', 'key1': 'a00'}]}
kaynak:
Replacing values in a Python list/dictionary?
http://stackoverflow.com/questions/1076536/replacing-values-in-a-python-list-dictionary
Hiç yorum yok:
Yorum Gönder