Python Dictionary -index numbering is different every time - python

I'm using python 2.7\ Linux
I have api result (see below):
{"id":"137","iv":0,
"components":[{"id":"928","type":"IDUGW","creation_date":"2016-05-04 08:10:38.0","update_date":"2016-05-04 08:10:38.0","unit_id":"137","serial_number":"00000000501C8349"},
{"id":"927","type":"IDU","creation_date":"2016-05-04 08:10:37.0","update_date":"2016-05-04 08:10:37.0","unit_id":"137","serial_number":"00000000501C8268"},
{"id":"930","type":"Battery","creation_date":"2016-05-04 08:10:40.0","update_date":"2016-05-04 08:10:40.0","unit_id":"137","serial_number":"00000000501C802A"}
,{"id":"929","type":"Panel","creation_date":"2016-05-04 08:10:39.0","update_date":"2016-05-04 08:10:39.0","unit_id":"137","serial_number":"00000000501C810B"}],
"creation_date":"2016-05-04 08:10:41.0",
"update_date":"2016-05-04 08:10:41.0",
"serial_number":"0011",
"phone_number":"972528745028",
"owner_phone":"9720545555554"}
if i understand it right, i have dictionary inside dictionary ( 2nd line "component" is another dictionary which has 4 key\values in it)
I'm trying to check if in dictionary the "type" equals to parameter i give.
Code:
if (MyDictionary[u'components'][0][u'type'] <> lRestParams['type4']):
i have 4 index (0,1,2,3)
sometimes the "if" pass, and sometimes the index is changed (when rebuilding everything) and it fails
how can i compare type4 to MyDictionary[u'components'][one of index][u'type']
In addition i need to compare after that that the value of the key = value4
so it means that if we check index x than key and value should be checked there.
Hope not to complicated
Thanks in advance
Ohad

Instead of giving the index number, you can loop through the component values to do the comparision.
for keys in data['components']:
if keys['type'] == "IDUGW":
print "matched"

Related

dict with one key and multiple values

I was wondering if there's a way for me to pull a value at a specific index. Let's say I have a key with multiple values associated with it. But in my dictionary I have multiple keys, each key with multiple values. I want to iterate through the keys and then each respective value associated with that key. I want to be able to pull the value at the first index and subtract it from the value at the second index.
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
output for key 108572791 would be -1.33
output for key 108577388 would be -.03
I've try reading up on dict and how it works apparently you can't really index it. I just wanted to know if there's a way to get around that.
for key, values in total_iteritems():
for value in values:
value[0]-value[1]:
Edit:
Since the question is way different now, I'll address the new subject:
d= {108572791: [200356.77, 200358], 108577388: [19168.7, 19169]}
for i in d:
print("Output for key ",str(i), "would be ",(d[i][1]-d[i][0]))
Output:
Output for key 108572791 would be 1.2300000000104774
Output for key 108577388 would be 0.2999999999992724
Original answer
Yes. When you have a dict containing a list as value if you want to obtain a specific value, then you need to address the index in the list. An example is:
a = {'Name':['John','Max','Robert']}
This means that:
print(a['Name'])
Output:
['John','Max','Robert']
Since ['Name'] is a list:
for i in range(len(a['Name'])):
print(a['Name'][i]
Output:
John #(Because it's the index 0)
Max #(Index = 1)
Robert #(Index = 2)
If you want a specific value (for instance 'Max' which is index = 1)
print(a['Name'][1]
Output:
Max
Depends on how many values in key obvious but this does the trick:
for x in d:
print(x)
print(d[x][0]-d[x][1])
You can use list of tuples if you want to use indexing.
d= [(108572791,[200356.77, 200358]), (108577388,[19168.7, 19169)]
for tuple in my_list:
print(tuple[0])
for value in tuple[1]:
print(value)

Dictionary access is stopping the code flow

I have a 3 seperate dictionaries that I manually enter values into. There is a loop that shows the value associated with the keys depending on a if condition
inv_dict_celltype and buf_dict_celltype are dictioanries. From the code below i observe that when i try to access both the dictionaries in different scenarios the code doesn't work. The output I get shows the dictionary values present in the first statement I give here, I get all the values in inv_dect_celltype but it doesn't proceed with next if statement, instead comes out
And the temp_list contains the following data :
temp_list = {'INV_X20B_NXP7P5PP96PTL_C16', 'INV_X6B_NXP7P5PP96PTL_C16',
'INV_X8B_NXP7P5PP96PTL_C16', 'INV_X16B_NXP7P5PP96PTL_C16',
'INV_X10B_NXP7P5PP96PTL_C16', 'BUF_X6N_A7P5PP96PTL_C16',
'BUF_X20N_A7P5PP96PTL_C16', 'BUF_X8N_A7P5PP96PTL_C16',
'BUF_X10N_A7P5PP96PTL_C16', 'BUF_X7N_A7P5PP96PTL_C16',
'BUF_X1P3N_A7P5PP96PTS_C18'}
for each_cell in temp_list:
if each_cell.startswith('INV_'):
print(inv_dict_celltype[each_cell])
if each_cell.startswith('BUF_'):
print(buf_dict_celltype[each_cell])
I am not sure what exactly you want to retrieve from your dictionaries, and how the other two dictionaries look like, but try with the following.
for each_cell in temp_list:
if each_cell.startswith('INV_'):
for i in inv_dict_celltype:
if i == each_cell:
print(i)
if each_cell.startswith('BUF_'):
for x in buf_dict_celltype:
if x == each_cell:
print(x)

Python: Sorting ip ranges which are dictionary keys

I have a dictionary which has IP address ranges as Keys (used to de-duplicate in a previous step) and certain objects as values. Here's an example
Part of the dictionary sresult:
10.102.152.64-10.102.152.95 object1:object3
10.102.158.0-10.102.158.255 object2:object5:object4
10.102.158.0-10.102.158.31 object3:object4
10.102.159.0-10.102.255.255 object6
There are tens of thousands of lines, I want to sort (correctly) by IP address in keys
I tried splitting the key based on the range separator - to get a single IP address that can be sorted as follows:
ips={}
for key in sresult:
if '-' in key:
l = key.split('-')[0]
ips[l] = key
else:
ips[1] = key
And then using code found on another post, sorting by IP address and then looking up the values in the original dictionary:
sips = sorted(ipaddress.ip_address(line.strip()) for line in ips)
for x in sips:
print("SRC: "+ips[str(x)], "OBJECT: "+" :".join(list(set(sresult[ips[str(x)]]))), sep=",")
The problem I have encountered is that when I split the original range and add the sorted first IPs as new keys in another dictionary, I de-duplicate again losing lines of data - lines 2 & 3 in the example
line 1 10.102.152.64 -10.102.152.95
line 2 10.102.158.0 -10.102.158.255
line 3 10.102.158.0 -10.102.158.31
line 4 10.102.159.0 -10.102.255.25
becomes
line 1 10.102.152.64 -10.102.152.95
line 3 10.102.158.0 -10.102.158.31
line 4 10.102.159.0 -10.102.255.25
So upon rebuilding the original dictionary using the IP address sorted keys, I have lost data
Can anyone help please?
EDIT This post now consists of three parts:
1) A bit of information about dictionaries that you will need in order to understand the rest.
2) An analysis of your code, and how you could fix it without using any other Python features.
3) What I would consider the best solution to the problem, in detail.
1) Dictionaries
Python dictionaries are not ordered. If I have a dictionary like this:
dictionary = {"one": 1, "two": 2}
And I loop through dictionary.items(), I could get "one": 1 first, or I could get "two": 2 first. I don't know.
Every Python dictionary implicitly has two lists associated with it: a list of it's keys and a list of its values. You can get them list this:
print(list(dictionary.keys()))
print(list(dictionary.values()))
These lists do have an ordering. So they can be sorted. Of course, doing so won't change the original dictionary, however.
Your Code
What you realised is that in your case you only want to sort according to the first IP address in your dictionaries keys. Therefore, the strategy that you adopted is roughly as follows:
1) Build a new dictionary, where the keys are only this first part.
2) Get that list of keys from the dictionary.
3) Sort that list of keys.
4) Query the original dictionary for the values.
This approach will, as you noticed, fail at step 1. Because as soon as you made the new dictionary with truncated keys, you will have lost the ability to differentiate between some keys that were only different at the end. Every dictionary key must be unique.
A better strategy would be:
1) Build a function which can represent you "full" ip addresses with as an ip_address object.
2) Sort the list of dictionary keys (original dictionary, don't make a new one).
3) Query the dictionary in order.
Let's look at how we could change your code to implement step 1.
def represent(full_ip):
if '-' in full_ip:
# Stylistic note, never use o or l as variable names.
# They look just like 0 and 1.
first_part = full_ip.split('-')[0]
return ipaddress.ip_address(first_part.strip())
Now that we have a way to represent the full IP addresses, we can sort them according to this shortened version, without having to actually change the keys at all. All we have to do is tell Python's sorted method how we want the key to be represented, using the key parameter (NB, this key parameter has nothing to do with key in a dictionary. They just both happened to be called key.):
# Another stylistic note, always use .keys() when looping over dictionary keys. Explicit is better than implicit.
sips = sorted(sresults.keys(), key=represent)
And if this ipaddress library works, there should be no problems up to here. The remainder of your code you can use as is.
Part 3 The best solution
Whenever you are dealing with sorting something, it's always easiest to think about a much simpler problem: given two items, how would I compare them? Python gives us a way to do this. What we have to do is implement two data model methods called
__le__
and
__eq__
Let's try doing that:
class IPAddress:
def __init__(self, ip_address):
self.ip_address = ip_address # This will be the full IP address
def __le__(self, other):
""" Is this object less than or equal to the other one?"""
# First, let's find the first parts of the ip addresses
this_first_ip = self.ip_address.split("-")[0]
other_first_ip = other.ip_address.split("-")[0]
# Now let's put them into the external library
this_object = ipaddress.ip_address(this_first_ip)
other_object = ipaddress.ip_adress(other_first_ip)
return this_object <= other_object
def __eq__(self, other):
"""Are the two objects equal?"""
return self.ip_address == other.ip_adress
Cool, we have a class. Now, the data model methods will automatically be invoked any time I use "<" or "<=" or "==". Let's check that it is working:
test_ip_1 = IPAddress("10.102.152.64-10.102.152.95")
test_ip_2 = IPAddress("10.102.158.0-10.102.158.255")
print(test_ip_1 <= test_ip_2)
Now, the beauty of these data model methods is that Pythons "sort" and "sorted" will use them as well:
dictionary_keys = sresult.keys()
dictionary_key_objects = [IPAddress(key) for key in dictionary_keys]
sorted_dictionary_key_objects = sorted(dictionary_key_objects)
# According to you latest comment, the line below is what you are missing
sorted_dictionary_keys = [object.ip_address for object in sorted_dictionary_key_objects]
And now you can do:
for key in sorted_dictionary_keys:
print(key)
print(sresults[key])
The Python data model is almost the defining feature of Python. I'd recommend reading about it.

Accessing an index/value inside a key (Python)

I've got a dictionary with 18 different keys, each has 3 values inside (xPower, xPP and xAccuracy) each variable holds an int. How would I access one value from a certain key? For example, I want to take out the value of ScratchPower (40) for use elsewhere. After searching for over half an hour the most I have found is accessing all the values from a key:
print defMoves["Scratch"]
Here is my dictionary:
defMoves = {
"Scratch": [ScratchPower, ScratchPP, ScratchAccuracy],
"Air Slash": [Air_SlashPower, Air_SlashPP, Air_SlashAccuracy],
"Flare Blitz": [Flare_BlitzPower, Flare_BlitzPP, Flare_BlitzAccuracy],
"Growl": [GrowlPower, GrowlPP, GrowlAccuracy],
"Heat Wave": [Heat_WavePower, Heat_WavePP, Heat_WaveAccuracy],
"Ember": [EmberPower, EmberPP, EmberAccuracy],
"Shadow Claw": [Shadow_ClawPower, Shadow_ClawPP, Shadow_ClawAccuracy],
"Smokescreen": [SmokescreenPower, SmokescreenPP, SmokescreenAccuracy],
"Dragon Claw": [Dragon_ClawPower, Dragon_ClawPP, Dragon_ClawAccuracy],
"Dragon Rage": [Dragon_RagePower, Dragon_RagePP, Dragon_RageAccuracy],
"Scary Face": [Scary_FacePower, Scary_FacePP, Scary_FaceAccuracy],
"Fire Fang": [Fire_FangPower, Fire_FangPP, Fire_FangAccuracy],
"Flame Burst": [Flame_BurstPower, Flame_BurstPP, Flame_BurstAccuracy],
"Wing Attack": [Wing_AttackPower, Wing_AttackPP, Wing_AttackAccuracy],
"Slash": [SlashPower, SlashPP, SlashAccuracy],
"Flamethrower": [FlamethrowerPower, FlamethrowerPP, FlamethrowerAccuracy],
"Fire Spin": [Fire_SpinPower, Fire_SpinPP, Fire_SpinAccuracy],
"Inferno": [InfernoPower, InfernoPP, InfernoAccuracy],
}
Thanks
defMoves["Scratch"] returns a list so just index like you would any list:
defMoves["Scratch"][0] # first subelement -> ScratchPower
defMoves["Scratch"][1] # second subelement -> ScratchPP
defMoves["Scratch"][2] # third subelement -> ScratchAccuracy
......
defMoves["Scratch"] gets you back the value, which in this case is a list, associated with that key. To get a specific item from that list, you need to use a numeric index. So, for example, to get ScratchPower, you'd use defMoves["Scratch"][0].
That seems hard to keep track of, though, so you may want to use another dictionary inside each of these dictionaries. That'd look like
{"Scratch" : {"Power":40... }... }

python: print values from a dictionary

generic_drugs_mapping={'MORPHINE':[86],
'OXYCODONE':[87],
'OXYMORPHONE':[99],
'METHADONE':[82],
'BUPRENORPHINE':[28],
'HYDROMORPHONE':[54],
'CODEINE':[37],
'HYDROCODONE':[55]}
How do I return 86?
This does not seem to work:
print generic_drugs_mapping['MORPHINE'[0]]
You have a bracket in the wrong place:
print generic_drugs_mapping['MORPHINE'][0]
Your code is indexing the string 'MORPHINE', so it's equivalent to
print generic_drugs_mapping['M']
Since 'M' is not a key in your dictionary, you won't get the results you expect.
The list is the value stored under the key. The part that gets the value out is generic_drugs_mapping['MORPHINE'] so this has the value [86]. Try moving the index outside like this :
generic_drugs_mapping['MORPHINE'][0]

Categories

Resources