I have a simple dictionary in python and I want to iterate over all of the items to print the key and value:
myDictionary = {"0" :0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":12, "7":0,"8":0,"9":0,"10":0,"11":0, "12":0,"13":12}
def count(self, myDictionary):
for k, v in myDictionary.items():
print k,v
Python sees myDictionary as:
{'11': 0, '10': 0, '13': 12, '12': 0, '1': 0, '0': 0, '3': 0, '2': 0, '5': 0, '4': 0, '7': 0, '6': 12, '9': 0, '8': 0}
When the keys and values print out though, only 11 0 print. I also tried iteritems(). Why is only the first element in the dictionary being printed? I have python 2.3 if that makes a difference.
I made the assumption (based on the comments) that this snippet of code does not belong to a dictionary class but is rather a method, so I removed self (which is used to call other variables or methods within the class itself) and saw that the following code returned the result you wanted (running python 2.7.3):
>>>def count(myDictionary):
for k,v in myDictionary.items():
print k,v
>>>count(myDictionary)
11 0
10 0
13 12
12 0
1 0
0 0
3 0
2 0
5 0
4 0
7 0
6 12
9 0
8 0
>>>
This supports the need to update to 2.7x and to remove self when you call your method with just one dictionary (myDictionary) otherwise it will expect two arguments.
If you need the data to be stored in a class structure that can indeed be accomplished but I would only recommend that for a data structure more complicated than the one you posted such as a keyed dictionary where each key has multiple attributes that you would want to call separately. Such as:
dictionary = {v1: 0, 8, 9, v2: 9,6,3}
Where v1, and v2 represent 3D vectors with x, y, and z directions which you want to call individually without having to cycle through all of the data.
Related
I'm having trouble accessing multiple values in a dictionary. Let's say I have this dictionary:
{'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}
I want to find two keys that sum to 6 and display their values. Here, the keys 4 and 2 add to 6, so the 2 values are 3 and 1.
Where do I start? This is the code I have so far:
for key in dico:
if sum(key + key) == 6:
print(f"Numbers # {key:dico} have a sum of 6")
No need for extra loops (or itertools), they will only slow your program down. You already know what the other index needs to be (because you can subtract the index from 6), so just check if that index exists:
dct = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}
for i, key in enumerate(dct):
if i + 2 > len(dct)/2:
break
matchIndex = str(6 - int(key))
if dct.get(matchIndex) is not None:
print(f'Keys {key} and {matchIndex} have values {dct[key]} and {dct[matchIndex]}')
This approach has a O(n/2) time complexity, while the other answer has O(n^2) time complexity.
When I tested this approach with timeit, it took 1.72 seconds to run this answer one million times, but the itertools answer took 5.83 secondss.
You will need to compare each of the dictionary keys with the rest of the other keys. You can use itertools for this.
As you mention you would like to print the value of each of the keys you have in your dictionary, it would be something like this:
import itertools
dico = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}
for a, b in itertools.combinations(dico.keys(), 2):
if int(a) + int(b) == 6:
print(f"{dico[a]} - {dico[b]}")
You need two loops for that.
Also, have in mind that there is more than one answer to that problem
a = {'1': 0, '2': 1, '3': 2, '4': 3, '5': 4, '6': 5}
results = list()
for key_1 in a.keys():
for key_2 in a.keys():
if key_1 != key_2:
if a[key_1] + a[key_2] == 6:
if a[key_1] < a[key_2]:
results.append((key_1, key_2))
print(results)
I’m trying to take a list of numbers, separate the values into dictionaries based on the int and float types, and then count the number of their occurrences. I’m having issues with the logic.
With the ideal output looking like so:
'int' : [1 : 3, 2 : 4, 5 : 1, 6 : 2],
'float' : [1.0 : 2, 2.3 : 4, 3.4 : 4]
This is what I have so far, and I keep pounding my head:
values = [1, 2.0, 3.0, 1, 1, 3, 4.0, 2, 1.0]
types = {
'int': [],
'float': []
}
for obj in values:
if isinstance(obj, int):
types['int'].append(obj)
elif isinstance(obj, float):
types['float'].append(obj)
for v in types:
if v not in types['int']:
counts = 0
counts[v] += 1
elif v not in types['float']:
counts = 0
counts[v] += 1
print(counts)
With the ideal output being:
'int' : [1 : 3, 2 : 4, 5 : 1, 6 : 2],
'float' : [1.0 : 2, 2.3 : 4, 3.4 : 4]
First half seems fine, but second half can improve.
try:
for k,v in types.items():
print(k, len(v))
Sample input:
values = [1.1,2,3.1]
Gives this output:
int 1
float 2
How about something like this:
This leverages the type function to give you the keys for the resulting array ('int' and 'float') without having to specify those strings.
numbers = [1,1,1,2.1,2.1,2.2, 3,3.1]
def tally_by_type(numbers):
result = {}
for v in numbers:
k = type(v).__name__
result[k] = result.get(k, {})
result[k][v] = result[k].get(v,0)
result[k][v] = result[k][v] + 1
return result
tally_by_type(numbers)
{'int': {1: 3, 3: 1}, 'float': {2.1: 2, 2.2: 1, 3.1: 1}}
Interestingly, this also works if you have strings in there
tally_by_type([1,2,3,3,3,'a','a','b'])
{'int': {1: 1, 2: 1, 3: 3}, 'str': {'a': 2, 'b': 1}}
you can try something like this:
ints={}
floats={}
list=[3.5,27,87.8,1.02,66]
for val in list:
if isinstance(val,int):
ints[str(val)]=val
elif isinstance(val,float):
floats[str(val)]=val
print("ints dictionary\n",ints,"number of instances",len(ints))
print("floats dictionary\n",floats,"number of instances",len(floats))
which prints:
ints dictionary
{'27': 27, '66': 66} number of instances 2
floats dictionary
{'3.5': 3.5, '87.8': 87.8, '1.02': 1.02} number of instances 3
I did not quite get what dictionary keys you want to use though, assumed you don't really need them.
By the following program, I am trying to calculate the number of occurance of '0','1','2',and '3' for each column. The program is not working as desired. I read somewhere that slicing of the matrix should be done for computing the occurance column wise but I am not sure how to do it. The program is written using numpy in python. How to do it using numpy?
import numpy as np
a=np.array([[ 2,1,1,2,1,1,2], #t1 is horizontal
[1,1,2,2,1,1,1],
[2,1,1,1,1,2,1],
[3,3,3,2,3,3,3],
[3,3,2,3,3,3,2],
[3,3,3,2,2,2,3],
[3,2,2,1,1,1,0]])
print(a)
i=0
j=0
two=0
zero=0
one=0
three=0
r=a.shape[0]
c=a.shape[1]
for i in range(1,r):
#print(repr(a))
for j in range(1,c):
#sele=a[i,j]
if (a[i,j]==0):
zero+=1
if (a[i,j]==1):
one+=1
if (a[i,j]==2):
two+=1
if (a[i,j]==3):
three+=1
if i==c-1:
#print(zero)
print(one)
i+=0
j=j+1
#print(two)
#print(three)
i=i+1
#print(zero)`
Also I want to print it in the following manner:
column: 0 1 2 3 4 5 6
occurrences: 0 0 0 0 0 0 0 1
1 1 3 2 2 4 3 1
2 2 1 3 4 1 2 2
3 4 3 2 1 2 2 2
Here is the code using list functionality
import numpy as np
inputArr=np.array([[ 2,1,1,2,1,1,2],
[1,1,2,2,1,1,1],
[2,1,1,1,1,2,1],
[3,3,3,2,3,3,3],
[3,3,2,3,3,3,2],
[3,3,3,2,2,2,3],
[3,2,2,1,1,1,0]
])
occurance = dict()
toFindList = [0,1,2,3]
for col in range(len(inputArr)):
collist = inputArr[:, col]
collist = (list(collist))
occurance['col_' + str(col)] = {}
for num in toFindList:
occurcount = collist.count(num)
occurance['col_' + str(col)][str(num)] = occurcount
for key, value in occurance.iteritems():
print key, value
Output:
col_2 {'1': 2, '0': 0, '3': 2, '2': 3}
col_3 {'1': 2, '0': 0, '3': 1, '2': 4}
col_0 {'1': 1, '0': 0, '3': 4, '2': 2}
col_1 {'1': 3, '0': 0, '3': 3, '2': 1}
col_6 {'1': 2, '0': 1, '3': 2, '2': 2}
col_4 {'1': 4, '0': 0, '3': 2, '2': 1}
col_5 {'1': 3, '0': 0, '3': 2, '2': 2}
This should give you the output format you want:
def col_unique(a):
return np.sum(np.dstack([np.in1d(a,i).reshape(a.shape) for i in np.unique(a)]), axis = 0).T
Given the following array:
a = []
a.append({'c': 1, 'v': 10, 'p': 4})
a.append({'c': 2, 'v': 10, 'p': 4})
a.append({'c': 3, 'v': 10, 'p': None})
a.append({'c': 4, 'v': 0, 'p': None})
a.append({'c': 5, 'v': 10, 'p': 1})
a.append({'c': 6, 'v': 10, 'p': 1})
Where c = code, v= value and p=parent
table looks like that:
c v p
1 4
2 10 4
3 10
4
5 10 1
6 10 1
I have to sum up each parent with the values of it's children
Expected result table would be:
c v p
1 20 4
2 10 4
3 10
4 30
5 10 1
6 10 1
How to achieve this?
First, you should derive another dictionary, mapping parents to lists of their children, instead of children to their parents. You can use collections.defaultdict for this.
from collections import defaultdict
children = defaultdict(list)
for d in a:
children[d["p"]].append(d["c"])
Also, I suggest another dictionary, mapping codes to their values, so you don't have to search the entire list each time:
values = {}
for d in a:
values[d["c"]] = d["v"]
Now you can very easily define a recursive function for calculating the total value. Note, however, that this will do some redundant calculations. If your data is much larger, you might want to circumvent this by using a bit of memoization.
def total_value(x):
v = values[x]
for c in children[x]:
v += total_value(c)
return v
Finally, using this function in a dict comprehension gives you the total values for each code:
>>> {x: total_value(x) for x in values}
{1: 30, 2: 10, 3: 10, 4: 40, 5: 10, 6: 10}
I have a dictionary that has Key:Values.
The values are integers. I would like to get a sum of the values based on a condition...say all values > 0 (i.e).
I've tried few variations, but nothing seems to work unfortunately.
Try using the values method on the dictionary (which returns a generator in Python 3.x), iterating through each value and summing if it is greater than 0 (or whatever your condition is):
In [1]: d = {'one': 1, 'two': 2, 'twenty': 20, 'negative 4': -4}
In [2]: sum(v for v in d.values() if v > 0)
Out[2]: 23
>>> a = {'a' : 5, 'b': 8}
>>> sum(value for _, value in a.items() if value > 0)