How to make my code more simple using python - python

this is my code:
def set_floor_point(self,floor_point=None):
if self.data.get('stage'):
self.data['stage'] = {}
stage_number = self.get_stage_number()
floor_number = self.get_floor_number()
if self.data['stage'].get(stage_number):
self.data['stage'][stage_number] = {}
if self.data['stage'][stage_number].get('floor_point'):
self.data['stage'][stage_number]['floor_point'] = {}
if self.data['stage'][stage_number]['floor_point'].get(floor_number):
self.data['stage'][stage_number]['floor_point'][floor_number] = {}
self.data['stage'][stage_number]['floor_point'][floor_number] = floor_point
and the dict i create when first time is like this :
stage =
{
0:{
'floor':{
0:{
'floor_point':0,
'gift':{}
}
}
}
}
but i think my code is not very good , it is too Cumbersome,
so Are someone know more simple way ,
thanks

data = collections.defaultdict(lambda: collections.defaultdict(
lambda: collections.defaultdict(dict)))
data['stage'][3]['floor_point'][2] = 5
print data

I'm not sure what you want to achieve. A recurring theme in your code is:
if some_dict.get(key):
some_dict[key] = {}
That means: if some_dict has a key key and some_dict[key] is a truthy value, then replace some_dict[key] by {}. If some_dict doesn't have a key key or some_dict[key] is a falsy value (None, 0, False, [] etc.), then do nothing.
If that is what you wanted, you could clarify your like this:
def replace_value_by_empty_dict(d, key):
if d.get(key):
d[key] = {}
...
replace_value_by_empty_dict(self.data, 'stage')
etc.
But if that's not what you intended (the code will break if one of the ifs is true), you might want to phrase the problem in english words or pseudocode to clarify the structure of the problem.
And have a look at collections.defaultdict.

Related

Recursive search JSON/DICT in Python 3

I am realizing in Python 3 some APIs that allow me to receive information about a school based on the class code. But I would like to know how I get the information through the class code.
Example:
I enter the code GF528S and I want the program to tell me the class (3C INF), the address (Address 1, Milan), and if possible also the name of the school (Test School 1) and the previous keys. Thanks in advance! Of course I use a JSON structure:
{
"schools": {
"Lombardia": {
"Milano": {
"Milano": {
"Test School 1": {
"sedi": {
"0": {
"indirizzo": "Address 1, Milan",
"classi": {
"INFORMATICA E TELECOMUNICAZIONI": {
"3C INF": "GF528S"
}
}
},
"1": {
"indirizzo": "Address 2, Milan",
"classi": {
"INFORMATICA E TELECOMUNICAZIONI": {
"1A IT": "HKPV5P",
"2A IT": "QL3J3K",
"3A INF": "X4E35C",
"3A TEL": "ZAA7LC"
}
}
}
}
}
}
}
}
}
}
When I get the values ​​from my database they are converted to a python dictionary if it helps!
After a series of tests thanks to your answers, I found that the for in .items() is blocked when it shows the indirizzo field:
In particular, it cannot search in these dictionaries:
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'3C INF': 'GF528S'}}, 'indirizzo': 'Address 1, Milan'}
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'1A IT': 'HKPV5P', '2A IT': 'QL3J3K', '3A INF': 'X4E35C', '3A TEL': 'ZAA7LC'}}, 'indirizzo': 'Address 2, Milan'}
I think the problem is precisely the indirizzo field. If you want to do the for first, it can be saved in a variable and deleted from the json:
del val ["address"]
The problem is that then I can't associate the address with the class.
Code:
def dictionary_check(input):
indirizzo = ""
for key,value in input.items():
if isinstance(value, dict):
dictionary_check(value)
else:
for i in value:
indirizzo += i["indirizzo"]
del i['indirizzo']
for x, y in i.items():
for z, j in y.items():
for a in j.items():
if a[1] == "HKPV5P":
print(indirizzo)
print("Classe: " + a[0])
While I can't write the exact code for you, I think it's reasonable to be able to give you a rough idea of what the code would look like, and some guidance.
I don't exactly know where this JSON data is being obtained. So it may have more / less keys when your applications runs. However, assuming the json is exactly as is, and the json data is loaded onto the variable (let's say json_map), then accessing a specific value looks something like:
json_map[key_value]
So you would want to do something similar to
json_map['schools']['Lombardia']['Milano']
and more keys until you reach the dictionary you want to play around with.
I think the point you might be confused is - if you have multiple values (that you may not be aware of what they might look like) how you handle it. For example, I think the key "sedi" (which I assume means locations) might return multiple locations (i.e. schools) and you won't know what their keys / values are. In that case, you may wish to iterate through that dictionary via something like:
for key, value in dict_.items():
# do your action
it is likely that key will be an integer (in string format) and value will be another dictionary. You will want to check a specific attribute of the dictionary to see if it's the one you're looking for.
Also, finally, when you get to the 'INFORMATICA E TELECOMUNICAZIONI' dictionary of the location(s), you may wish to return the key of the item that has the corresponding value. Something like:
for key, value in dict_.items():
if value == 'GF528S':
return key
Of course, you'll be able to replace this value of 'GF528S' to a variable so you can change it each time.
I think this is as far as I can help you without actually implementing this. I gave the benefit of the doubt that you are like me when I just started programming and I just needed someone to give me a rough outline of what to do. Any more help, I think you may need grab someone who has knowledge of what to do IRL or hire a tutor/teacher to teach you basic concepts of Programming.
search_key = "GF528S"
def recursive_search(dct,keys):
for key,value in dct.items():
if key == search_key:
print(keys,value)
if type(value) == dict:
recursive_search(value,[*keys,key])
recursive_search(dinput_dict,[])
You should use recursive function to find key or value.
def search_key(data, key, path=""):
if type(data) is dict:
for k, v in data.items():
path="{0} -> {1}".format(path, k)
if k == key or v == key:
return (k, v, path)
res = search_key(data[k], key, path)
if res is not None:
return res
result = search_key(your_dictionary, key="GF528S")
if result is not None:
print("key:", result[0])
print("value:", result[1])
print("path:", result[2])
else:
print("key or value not found!")
If you want to search entire of dictionary and get all duplicate keys or values using given pattern key, this below function is useful.
def entire_search_key(data, key, founds=[], path=""):
if type(data) is dict:
for k, v in data.items():
path="{0} -> {1}".format(path, k)
if k == key or v == key:
founds.append((k, v, path))
entire_search_key(data[k], key, founds, path)
return founds
result = entire_search_key(your_dictionary, key="ddd")
if result == []:
print("key or value not found!")
else:
for i in result:
print(i)

Remove the key value pairs based on value

a:{
b:{cd:"abc",
de:"rty"
},
c:{cd:"abc",
de:"uuy"
},
d:{cd:"ap",
de:"uy"
}
}
I want to print values of cd and de from this dictionary and if the value of cd is same then I only want to print once.
Expected output: b abc rty
d ap uy
How can I check if the value of cd is repeated or not ?
Edit :
hash_set=set()
hash_item=v1.get('query_hash',{}).get('sha256', "")
if hash_item in hash_set:
break
else:
hash_set.add(hash_item)
This is not working
How can I check if the value of cd is repeated or not ?
If you are iterating over stuff and you don't want to process duplicates keep a container of things you have already seen and skip items if they have been seen. sets are excellent containers for membership testing as the look-up is O(1) and sets don't allow duplicates.
Here is a toy example.
stuff = 'anjdusttnnssajd'
seen = set()
for thing in stuff:
if thing in seen:
continue
print(thing.upper()) # process thing
seen.add(thing)
Or you could just make a set of the things to process then process the things in the set.
stuff = set(stuff)
for thing in stuff:
print(thing.upper())
Using your criteria.
d = {'a':{'b':{'cd':"abc",'de':"rty"},
'c':{'cd':"abc",'de':"uuy"},
'd':{'cd':"ap",'de':"uy"}}}
seen = set()
for key,thing in d['a'].items():
cd,de = thing['cd'],thing['de']
if cd in seen:
continue
else:
print(key, cd, de)
seen.add(cd)
This code should help, I formated your JSON a little bit for it to be a valid python string but you should be able to modify it as you wish
def getKeys(dict):
return [*dict]
a = {
'b':{'cd':"abc",
'de':"rty"
},
'c':{'cd':"abc",
'de':"uuy"
},
'd':{'cd':"ap",
'de':"uy"
}
}
cd_list = []
keys = getKeys(a)
for key in keys:
found = False
for checked in cd_list:
if a[key]['cd']==checked:
found = True
break
if not found:
print( f'{key} : {a[key]["cd"]} {a[key]["de"]}')
cd_list.append(a[key]['cd'])
you can try this
dict={'a':{
'b':{'cd':"abc",
'de':"rty"
},
'c':{'cd':"abc",
'de':"uuy"
},
'd':{'cd':"ap",
'de':"uy"
}
}}
count=0
for key,item in dict.items():
for key,i in item.items():
if item['b']['cd']==i['cd']:
count=count+1
lis=i['cd']
else:
print(i['cd'])
if(count>1):
print(lis)
here is your code
data = {"a":{"b":{"cd":"abc","de":"rty"},"c":{"cd":"abc","de":"uuy"},"d":{"cd":"ap","de":"uy"}}}
output = set()
for key,val in data.items():
for key1,val1 in val.items():
for key2, val2 in val1.items():
if val2 not in output:
output.add(key1)
output.add(val2)
else:
break
print(output)

How to check that only one value of my dictionary is filled?

How can I check that my dict contains only one value filled ?
I want to enter in my condition only if the value is the only one in my dict and of this type (in my example "test2") of my dict.
For now I have this if statement
my_dict = {}
my_dict["test1"] = ""
my_dict["test2"] = "example"
my_dict["test3"] = ""
my_dict["test4"] = ""
if my_dict["test2"] and not my_dict["test1"] and not my_dict["test3"] and not my_dict["test4"]:
print("inside")
I would like to find a better, classy and "pep8" way to achieve that
Any ideas ?
You have to check every value for truthiness, there's no way around that, e.g.
if sum(1 for v in my_dict.values() if v) == 1:
print('inside')
You can use filter() as below to check how many values are there in the dictionary.
if len(list(filter(None, my_dict.values()))) == 1:
print("inside")
Assuming that all your values are strings, what about
ref_key = "test2"
if ''.join(my_dict.values()) == my_dict[ref_key]:
print("inside")
... since it looks like you have a precise key in mind (when you do if my_dict["test2"]). Otherwise, my answer is (twice) less general than (some) others'.
Maybe you want to check if there's only one pair in dictionary after removing the empty values.
my_dict = {}
my_dict["test1"] = ""
my_dict["test2"] = "example"
my_dict["test3"] = ""
my_dict["test4"] = ""
my_dict={key:val for key,val in my_dict.items() if val}
if len(my_dict)==1:
print("inside")
Here is the another flavour (without loops):
data = list(my_dict.values())
if data.count('') + 1 == len(data):
print("Inside")

How to print one of dictonary values with specialized letter

I'm starting with Python.
I have the problem, because code not work like i want to do.
My target is to print for example if x = a i want to print 3. Is it possible to do without much effort?
dictonary1 = {
'a':3,
'b':4,
'c':5,
}
x = str(input("input a letter"))
for x in dictonary1:
print(x in dictonary1)
Now i get for all of keys
True
True
True
The best way to print (or use) a dictionary key if you are not sure it exists is:
print(dictonary1.get(x))
This way, if it doesn't exist, it will print (or produce) None, while if you use dictionary1[x] and the key doesn't exist, you will get an error.
This might work for you, i hope it helps:
answer=None
dictionary1 = { 'a':3, 'b':4, 'c':5, }
while answer==None:
try:
x = input("input a letter: ")
answer = dictionary1.get(x)
print(f"Dictionary answer to {x} is {answer}")
except:
answer=None

Finding matching keys in two large dictionaries and doing it fast

I am trying to find corresponding keys in two different dictionaries. Each has about 600k entries.
Say for example:
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
I want to print out the value for Actinobacter (8924342) since it matches a value in myRDP.
The following code works, but is very slow:
for key in myRDP:
for jey in myNames:
if key == jey:
print key, myNames[key]
I've tried the following but it always results in a KeyError:
for key in myRDP:
print myNames[key]
Is there perhaps a function implemented in C for doing this? I've googled around but nothing seems to work.
Thanks.
Use sets, because they have a built-in intersection method which ought to be quick:
myRDP = { 'Actinobacter': 'GATCGA...TCA', 'subtilus sp.': 'ATCGATT...ACT' }
myNames = { 'Actinobacter': '8924342' }
rdpSet = set(myRDP)
namesSet = set(myNames)
for name in rdpSet.intersection(namesSet):
print name, myNames[name]
# Prints: Actinobacter 8924342
You could do this:
for key in myRDP:
if key in myNames:
print key, myNames[key]
Your first attempt was slow because you were comparing every key in myRDP with every key in myNames. In algorithmic jargon, if myRDP has n elements and myNames has m elements, then that algorithm would take O(n×m) operations. For 600k elements each, this is 360,000,000,000 comparisons!
But testing whether a particular element is a key of a dictionary is fast -- in fact, this is one of the defining characteristics of dictionaries. In algorithmic terms, the key in dict test is O(1), or constant-time. So my algorithm will take O(n) time, which is one 600,000th of the time.
in python 3 you can just do
myNames.keys() & myRDP.keys()
for key in myRDP:
name = myNames.get(key, None)
if name:
print key, name
dict.get returns the default value you give it (in this case, None) if the key doesn't exist.
You could start by finding the common keys and then iterating over them. Set operations should be fast because they are implemented in C, at least in modern versions of Python.
common_keys = set(myRDP).intersection(myNames)
for key in common_keys:
print key, myNames[key]
Best and easiest way would be simply perform common set operations(Python 3).
a = {"a": 1, "b":2, "c":3, "d":4}
b = {"t1": 1, "b":2, "e":5, "c":3}
res = a.items() & b.items() # {('b', 2), ('c', 3)} For common Key and Value
res = {i[0]:i[1] for i in res} # In dict format
common_keys = a.keys() & b.keys() # {'b', 'c'}
Cheers!
Use the get method instead:
for key in myRDP:
value = myNames.get(key)
if value != None:
print key, "=", value
You can simply write this code and it will save the common key in a list.
common = [i for i in myRDP.keys() if i in myNames.keys()]
Copy both dictionaries into one dictionary/array. This makes sense as you have 1:1 related values. Then you need only one search, no comparison loop, and can access the related value directly.
Example Resulting Dictionary/Array:
[Name][Value1][Value2]
[Actinobacter][GATCGA...TCA][8924342]
[XYZbacter][BCABCA...ABC][43594344]
...
Here is my code for doing intersections, unions, differences, and other set operations on dictionaries:
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
if __name__ == '__main__':
import unittest
class TestDictDifferNoChanged(unittest.TestCase):
def setUp(self):
self.past = dict((k, 2*k) for k in range(5))
self.current = dict((k, 2*k) for k in range(3,8))
self.d = DictDiffer(self.current, self.past)
def testAdded(self):
self.assertEqual(self.d.added(), set((5,6,7)))
def testRemoved(self):
self.assertEqual(self.d.removed(), set((0,1,2)))
def testChanged(self):
self.assertEqual(self.d.changed(), set())
def testUnchanged(self):
self.assertEqual(self.d.unchanged(), set((3,4)))
class TestDictDifferNoCUnchanged(unittest.TestCase):
def setUp(self):
self.past = dict((k, 2*k) for k in range(5))
self.current = dict((k, 2*k+1) for k in range(3,8))
self.d = DictDiffer(self.current, self.past)
def testAdded(self):
self.assertEqual(self.d.added(), set((5,6,7)))
def testRemoved(self):
self.assertEqual(self.d.removed(), set((0,1,2)))
def testChanged(self):
self.assertEqual(self.d.changed(), set((3,4)))
def testUnchanged(self):
self.assertEqual(self.d.unchanged(), set())
unittest.main()
def combine_two_json(json_request, json_request2):
intersect = {}
for item in json_request.keys():
if item in json_request2.keys():
intersect[item]=json_request2.get(item)
return intersect

Categories

Resources