Obtaining key's index in python dictionary/hash table - python

I'm trying to obtain the key's index. Let's say i have:
Jamie: 3
Alan: 5
Dwayne: 4
and the keys are the names and values are the digits. What i want now is accessing the key's index in this case, the key Jamie is at index 0, Alan at 1 and Dwayne at 2.
I'm not familiar with this as I'm more used to obtaining the index from a normal list.
Do i do something like:
for i, value in enumerate(dict):
if dict[i] != ...
It doesn't seemed right and i'll appreciate some feedback on this.

As mentioned since dict doesn't store key,value pair in order by default, you will need to convert to orderedDict as below
>>> from collections import OrderedDict
>>> d = OrderedDict(d)
>>> d
OrderedDict([('Jamie', 3), ('Dwayne', 4), ('Alan', 5)])
After that dict's key index will be ordered
>>> d.keys()
['Jamie', 'Dwayne', 'Alan']
Then you can either use
>>> d.keys().index('Alan')
2
OR enumerate method that your are trying. ( Need to add iterator there)
>>> for i,value in enumerate(d.iteritems()):
print i,value
0 ('Jamie', 3)
1 ('Dwayne', 4)
2 ('Alan', 5)
>>>
Here you can access individual key,value as a 0,1 index of tuple.
>>> for i,value in enumerate(d.iteritems()):
print i, value[0], value[1]
0 Jamie 3
1 Dwayne 4
2 Alan 5
>>>

Are you looking for
for key in dict:
if key != ...
and you can use dict[key] to get corresponding value if the statement is met

Related

How to check if tuple key contains an element in dictionary

I am looking for an operation that could do something similar to this:
dict[ ( tuple[0] , _ ) ]
The dictionary contains tuples as keys.
How do I check if the dictionary contains a value where the tuple key has a specific value as the first part and any value as the second part?
Try this,
#Dictionary with tuples as keys
dict_with_tup = dict([((1,2),3), ((1,4),2), ((2,5),7)])
#value that you wanna find (just the first value of the tuple)
x = 1
#filtered dict based on that value
{k:v for k,v in dict_with_tup.items() if k[0]==x}
{(1, 2): 3, (1, 4): 2}
for a dictionary d
x = # value of interest
for key in d.keys():
if key[0] == x:
#do stuff
but as khelwood noted in the comments, it's not a very efficient way of doing things

Sum array values with specified index in Python

I have arrays like this:
['[camera_positive,3]', '[lens_positive,1]', '[camera_positive,2]', '[lens_positive,1]', '[lens_positive,1]', '[camera_positive,1]']
How to sum all value on index [1] with same string on index [0]?
Example:
camera_positive = 3 + 2 + 1 = 6
lens_positive = 1 + 1 + 1 = 3
You could use set in order to extract the unique keys and then use list comprehension to compute the sum for each key:
data = [['camera_positive', 3],
['lens_positive', 1],
['camera_positive', 2],
['lens_positive', 1],
['lens_positive', 1],
['camera_positive', 1]]
keys = set(key for key, value in data)
for key1 in keys:
total = sum(value for key2, value in data if key1 == key2)
print("key='{}', sum={}".format(key1, total))
this gives:
key='camera_positive', sum=6
key='lens_positive', sum=3
I'm assuming that you have a list of list, not a list of strings as shown in the question. Otherwise you'll have to do some parsing. That said, I would solve this problem by creating a dictionary, and then iterating over the values and adding them to the dictionary as you go.
The default dict allows this program to work without getting a key error, as it'll assume 0 if the key does not exist yet. You can read up on defaultdict here: https://docs.python.org/3.3/library/collections.html#collections.defaultdict
lmk if that helps!
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> d
defaultdict(<class 'int'>, {})
>>> lst=[['a',1], ['b', 2], ['a',4]]
>>> for k, v in lst:
... d[k] += v
...
>>> d
defaultdict(<class 'int'>, {'a': 5, 'b': 2})
You could group the entries by their first index using groupby with lambda x: x[0] or operator.itemgetter(0) as key.
This is maybe a bit less code than what Nick Brady showed. However you would need to sort the list first (for the same key), so it might be slower than his approach.

Add values to dict and increase list item's value by 1 if key is already in dict (python)

Adding values to a dict and using a simple if statement to + 1 to the value if the key exists works fine with the following:
d = {word: (frequency, wordList[1]) for frequency, word in sorteddict}
for key, value in d.items():
my_dict[key, value] = my_dict[key, value] + 1 if key in my_dict else value
I want to iterate over the dict "d" adding all the key value pairs to the dict "my_dict".
The problem I am having is that the dict's are key : list pairs and I only want to increase the value of list[0] if the key exists. For example:
d = {'smith': (1, 'jones')}
my_dict = {'smith': (2, 'jones')}
my_dict already contains the key 'smith' and so the logic would be:
+ 1 to list[0] else 1
to clarify the question and answer:
the problem is that there are 2 dicts d, my_dict. each values is a tuple containing 2 items. what we want is to generate a new dict which has the keys and values of d but with the first item of the value tuple increased by 1 if the key exists in my_dict or set to 1 if it doesn't. we will achieve that like this:
{x: (y[0] + 1 if x in my_dict else 1, y[1]) for x, y in d.items()}

Python. How to subtract 2 dictionaries

I have 2 dictionaries, A and B. A has 700000 key-value pairs and B has 560000 key-values pairs. All key-value pairs from B are present in A, but some keys in A are duplicates with different values and some have duplicated values but unique keys. I would like to subtract B from A, so I can get the remaining 140000 key-value pairs. When I subtract key-value pairs based on key identity, I remove lets say 150000 key-value pairs because of the repeated keys. I want to subtract key-value pairs based on the identity of BOTH key AND value for each key-value pair, so I get 140000. Any suggestion would be welcome.
This is an example:
A = {'10':1, '11':1, '12':1, '10':2, '11':2, '11':3}
B = {'11':1, '11':2}
I DO want to get:
A-B = {'10':1, '12':1, '10':2, '11':3}
I DO NOT want to get:
a) When based on keys:
{'10':1, '12':1, '10':2}
or
b) When based on values:
{'11':3}
To get items in A that are not in B, based just on key:
C = {k:v for k,v in A.items() if k not in B}
To get items in A that are not in B, based on key and value:
C = {k:v for k,v in A.items() if k not in B or v != B[k]}
To update A in place (as in A -= B) do:
from collections import deque
consume = deque(maxlen=0).extend
consume(A.pop(key, None) for key in B)
(Unlike using map() with A.pop, calling A.pop with a None default will not break if a key from B is not present in A. Also, unlike using all, this iterator consumer will iterate over all values, regardless of truthiness of the popped values.)
An easy, intuitive way to do this is
dict(set(a.items()) - set(b.items()))
A = {'10':1, '11':1, '12':1, '10':2, '11':2, '11':3}
B = {'11':1, '11':2}
You can't have duplicate keys in Python. If you run the above, it will get reduced to:
A={'11': 3, '10': 2, '12': 1}
B={'11': 2}
But to answer you question, to do A - B (based on dict keys):
all(map( A.pop, B)) # use all() so it works for Python 2 and 3.
print A # {'10': 2, '12': 1}
dict-views:
Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).
So you can:
>>> A = {'10':1, '11':1, '12':1, '10':2, '11':2, '11':3}
>>> B = {'11':1, '11':2}
>>> A.items() - B.items()
{('11', 3), ('12', 1), ('10', 2)}
>>> dict(A.items() - B.items())
{'11': 3, '12': 1, '10': 2}
For python 2 use dict.viewitems.
P.S. You can't have duplicate keys in dict.
>>> A = {'10':1, '11':1, '12':1, '10':2, '11':2, '11':3}
>>> A
{'10': 2, '11': 3, '12': 1}
>>> B = {'11':1, '11':2}
>>> B
{'11': 2}
Another way of using the efficiency of sets. This might be more multipurpose than the answer by #brien. His answer is very nice and concise, so I upvoted it.
diffKeys = set(a.keys()) - set(b.keys())
c = dict()
for key in diffKeys:
c[key] = a.get(key)
EDIT: There is the assumption here, based on the OP's question, that dict B is a subset of dict A, that the key/val pairs in B are in A. The above code will have unexpected results if you are not working strictly with a key/val subset. Thanks to Steven for pointing this out in his comment.
Since I can not (yet) comment: the accepted answer will fail if there are some keys in B not present in A.
Using dict.pop with a default would circumvent it (borrowed from How to remove a key from a Python dictionary?):
all(A.pop(k, None) for k in B)
or
tuple(A.pop(k, None) for k in B)
result = A.copy()
[result.pop(key) for key in B if B[key] == A[key]]
Based on only keys assuming A is a superset of B or B is a subset of A:
Python 3: c = {k:a[k] for k in a.keys() - b.keys()}
Python 2: c = {k:a[k] for k in list(set(a.keys())-set(b.keys()))}
Based on keys and can be used to update a in place as well #PaulMcG answer
For subtracting the dictionaries, you could do :
A.subtract(B)
Note: This will give you negative values in a situation where B has keys that A does not.

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?
(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)
You just have to use dict.values().
This will return a list containing all the values of your dictionary, without having to specify any key.
You may also be interested in:
.keys(): return a list containing the keys
.items(): return a list of tuples (key, value)
Note that in Python 3, returned value is not actually proper list but view object.
Other solution, using popitem and unpacking:
d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"
Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:
In Python 3 you can print the values, without knowing/using the keys, thus:
for item in my_dict:
print( list( item.values() )[0] )
Example:
cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']}
vals = list( cars.values() )
keyz = list( cars.keys() )
cnt = 0
for val in vals:
print('[_' + keyz[cnt] + '_]')
if len(val)>1:
for part in val:
print(part)
else:
print( val[0] )
cnt += 1
OUTPUT:
[_Toyota_]
Camry
Turcel
Tundra
Tacoma
[_Ford_]
Mustang
Capri
OrRepairDaily
[_Chev_]
Malibu
Corvette
That Py3 docs reference again:
https://docs.python.org/3.5/library/stdtypes.html#dict-views
Two more ways:
>>> d = {'k': 'v'}
>>> next(iter(d.values()))
'v'
>>> v, = d.values()
>>> v
'v'
One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.
>>>my_dict = {'a' : 25}
>>>for key in my_dict:
print(my_dict[key])
25
>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
print(my_other_dict[key])
33
44

Categories