Sum operation on dictionary python - python

I have a dictionary like this:
dict_connected_hosts = {
{'10.0.0.2': [[12564.0, 6844.0, 632711.0, 56589,0, 4856,0], <ryu.controller.controller.Datapath object at 0x7f2b2008a7d0>, '10.0.0.2', '10.0.0.1', 2, datetime.datetime(2017, 9, 26, 2, 24, 12, 301565)]}
{'10.0.0.3': [[3193.0, 621482.0, 6412.0, 2146.0, 98542.0], <ryu.controller.controller.Datapath object at 0x7f2b2008a7d0>, '10.0.0.3', '10.0.0.1', 3, datetime.datetime(2017, 9, 26, 2, 24, 12, 302224)]
{'10.0.0.7': [[4545.0, 51442.0, 325.0, 452.0, 3555.0], <ryu.controller.controller.Datapath object at 0x7f2b2008a7d0>, '10.0.0.7', '10.0.0.1', 3, datetime.datetime(2017, 9, 26, 2, 24, 12, 302250)]
}
how can I sum the first numbers of each list in the value field? In simple terms numbers
`12564.0 + 3193.0 + 4545.0`
thanks

I have debugged your dictionary structure. The relevant part of it should be :
{
'10.0.0.2': [[12564.0, 6844.0, 632711.0, 56589,0, 4856,0]],
'10.0.0.3': [[3193.0, 621482.0, 6412.0, 2146.0, 98542.0]],
'10.0.0.7': [[4545.0, 51442.0, 325.0, 452.0, 3555.0]]
}
Note : ignoring the other elements in the values as they are not relevant to the question (and they have errors I don't care to debug)
So, to get the sum of the first numbers in the first list of each value, you can do it by list comprehension :
#suppose `a` is the dictionary
print([val[0][0] for val in a.values()])
#[12564.0, 3193.0, 4545.0]
print(sum( [val[0][0] for val in a.values()] ))
#20302.0

Related

How do I select all the timing together with the name of the point at which the time occurs from a dictionary?

This is a section of the dictionary:
{'WayPoint46_WayPoint39': [(14.547985, datetime.datetime(2016, 5, 23, 18, 45, 47), True)], 'WayPoint39_WayPoint38': [(7.208904, datetime.datetime(2016, 5, 23, 18, 46, 13), True)], ... }
I want to select for example, WayPoint46_WayPoint39, 14.547985.
Thanks for helping in advance.
Probably the simpliest solution:
for key, value in input_dict.items():
print(key, value[0][0])
With input_dict equal to your input, the output looks like:
WayPoint46_WayPoint39 14.547985
WayPoint39_WayPoint38 7.208904
For sum you can use sum() function:
print(sum([value[0][0] for value in input_dict.values()]))

Strange output from ndarray.shape

I am trying to convert the value of a dictionary to a 1d array using:np.asarray(dict.values()), but when I tried to print the shape of the output array, I have problem.
My array looks like this:
dict_values([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26])
but the output of array.shape is:
()
by which I was expecting (27,1) or (27,)
after I changed the code to np.asarray(dict.values()).flatten(),the output of array.shape became
(1,)
I have read the document of numpy.ndarray.shape, but can't get a hint why the outputs are like these. Can someone explain it to me? Thx
This must be python 3.
From docs
The objects returned by dict.keys(), dict.values() and dict.items()
are view objects. They provide a dynamic view on the dictionary’s
entries, which means that when the dictionary changes, the view
reflects these changes.
The issue is that dict.values() is only returning a dynamic view of the data in dictionary's values, Leading to the behaviour you see.
dict_a = {'1': 1, '2': 2}
res = np.array(dict_a.values())
res.shape #()
res
#Output:
array(dict_values([1, 2]), dtype=object)
Notice that the numpy array isn't resolving the view object into the actual integers, but rather just coercing the view into an array with dtype = object
To avoid this issue, consume the view to get a list, as follows:
dict_a = {'1': 1, '2': 2}
res = np.array(list(dict_a.values()))
res.shape #(2,)
res #array([1, 2])
res.dtype #dtype('int32')

How do I make this into a for loop?

So basically I am trying to replace this:
board = {
0:[0, 1, 2, 9, 10, 11, 18, 19, 20],
1:[3, 4, 5, 12, 13, 14, 21, 22, 23],
2:[6, 7, 8, 15, 16, 17, 24, 25, 26]}
with a for loop that will automatically create it. Sorry if this seems obvious, but I'm a bit of a noob and I'm having a lot of trouble with this.
It looks like you're generating the first 27 integers (starting at 0) and then grouping them. Let's write it like that.
def group_by_threes(n=27, group_count=3):
# The end result will be a dict of lists. The number of lists
# is determined by `group_count`.
result = {}
for x in range(group_count):
result[x] = []
# Since we're using subgroups of 3, we iterate by threes:
for x in range(n // 3):
base = 3 * x
result[x % 3] += [base, base + 1, base + 2]
# And give back the answer!
return result
This code could be made better by making the size of groups (three in this case) an argument, but I'll leave that as an exercise to the reader. ;)
The advantage of this method is that it's much more modular and adaptable than just writing a one-off method that generates the exact list you're looking for. After all, if you only wanted to ever generate that one list you showed, then it'd probably be better to hardcode it!
def create_list(x):
a = [x,x+1,x+2,x+9,x+9+1,x+9+2,x+18,x+18+1,x+18+2]
return a
output = {}
for i in range(3):
output[i*3] = create_list(i*3)
print output
please try this you get desired output
def create_list(x):
res = []
for i in xrange(0,3):
for j in xrange(0,3):
res.append(3*x+ 9*i + j)
return res
dictionary={}
for i in xrange(0,3):
dictionary[i]=create_list(i)
print dictionary
Result:
{0: [0, 1, 2, 9, 10, 11, 18, 19, 20], 1: [3, 4, 5, 12, 13, 14, 21, 22, 23], 2: [6, 7, 8, 15, 16, 17, 24, 25, 26]}

How can I transfer a compiled tuple(rawly taken from Sql) in to a array, series, or a dataframe?

What I have is like this:
(('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)),
('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 )))
It is exactly the way it looks in mysql database.
What I want is like this:
[[1,2,3],
[4,5,6]]
It's okay to have a series, dataframe, array, list.etc. I just want it to be managable for further analysing process.
I've tried several ways to deal with this such as dataframe(),list(),even pandas.replace(and it gives me a tuple-cant-be-replaced error).
I'm new to python, thanks for your answers!:)))))))))
In case you have tuple of tuples you may try the following list comprehension
import datetime
input_tuple = (('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)),
('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 )))
output_list = [[i for i in j] for j in input_tuple]
print(output_list)

Python "Value Error: cannot delete array elements" -- Why am I getting this?

I haven't been able to find anything about this value error online and I am at a complete loss as to why my code is eliciting this response.
I have a large dictionary of around 50 keys. The value associated with each key is a 2D array of many elements of the form [datetime object, some other info]. A sample would look like this:
{'some_random_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]],
dtype=object),
'some_other_key': array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 'true'],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 'false']],
dtype=object)}
What I want my code to do is to allow a user to select a start and stop date and remove all of the array elements (for all of the keys) that are not within that range.
Placing print statements throughout the code I was able to deduce that it can find the dates that are out of range, but for some reason, the error occurs when it attempts to remove the element from the array.
Here is my code:
def selectDateRange(dictionary, start, stop):
#Make a clone dictionary to delete values from
theClone = dict(dictionary)
starting = datetime.strptime(start, '%d-%m-%Y') #put in datetime format
ending = datetime.strptime(stop+' '+ '23:59', '%d-%m-%Y %H:%M') #put in datetime format
#Get a list of all the keys in the dictionary
listOfKeys = theClone.keys()
#Go through each key in the list
for key in listOfKeys:
print key
#The value associate with each key is an array
innerAry = theClone[key]
#Loop through the array and . . .
for j, value in enumerate(reversed(innerAry)):
if (value[0] <= starting) or (value[0] >= ending):
#. . . delete anything that is not in the specified dateRange
del innerAry[j]
return theClone
This is the error message that I get:
ValueError: cannot delete array elements
and it occurs at the line: del innerAry[j]
Please help - perhaps you have the eye to see the problem where I cannot.
Thanks!
If you use numpy arrays, then use them as arrays and not as lists
numpy does comparison elementwise for the entire array, which can then be used to select the relevant subarray. This also removes the need for the inner loop.
>>> a = np.array([[datetime(2010, 10, 26, 11, 5, 28, 157404), 14.1],
[datetime(2010, 10, 26, 11, 5, 30, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 31, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 32, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 33, 613066), 17.2],
[datetime(2010, 10, 26, 11, 5, 38, 613066), 17.2]],
dtype=object)
>>> start = datetime(2010, 10, 26, 11, 5, 28, 157405)
>>> end = datetime(2010, 10, 26, 11, 5, 33, 613066)
>>> (a[:,0] > start)&(a[:,0] < end)
array([False, True, True, True, False, False], dtype=bool)
>>> a[(a[:,0] > start)&(a[:,0] < end)]
array([[2010-10-26 11:05:30.613066, 17.2],
[2010-10-26 11:05:31.613066, 17.2],
[2010-10-26 11:05:32.613066, 17.2]], dtype=object)
just to make sure we still have datetimes in there:
>>> b = a[(a[:,0] > start)&(a[:,0] < end)]
>>> b[0,0]
datetime.datetime(2010, 10, 26, 11, 5, 30, 613066)
NumPy arrays are fixed in size. Use lists instead.

Categories

Resources