Manipulating Dictionary Values Python - python

I have a dictionary with the following values.
d = {'a': 0, 'b': 1, 'c': 2}
print d['c']
This would print 2.
How would I go about changing the value for a given key word? So that when the keyword 'c' was given it would return something besides 2.

Just set it using the key:
>>> d = {'a': 0, 'b': 1, 'c': 2}
>>> print d['c']
2
>>> d['c'] = 9000
>>> print d['c']
9000

Related

How to read a tuple of dict keys

Say I have a a dictionary (e.g. d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}).
Say I want to read several keys of the dictionary, but not all (e.g. I want to read d['a'] and d['c']).
Here is the way I do it: (val_a, val_c) = (d[key] for key in ('a', 'c')).
Is there a more pythonic way to do this?
Use operator.itemgetter.
>>> from operator import itemgetter
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> get_ac = itemgetter('a', 'c')
>>> get_ac(d)
(1, 3)
Very similar to yours, but slightly shorter using map.
(Note: Just as with your approach, the result of map is not actually a tuple but a generator that is unpacked into multiple variables.)
>>> d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> a, c = map(d.get, ('a', 'c'))
>>> a, c
(1, 3)

Sorting a Dictionary in Python by two keys (frequency and lexicographically)

I have a dictionary in Python like this:
{'c': 3, 'b': 3, 'aa': 2, 'a': 2}
and I want to print it like this:
b
c
a
aa
I need to sort the dictionary first by the second key and if there are any collisions, sort them lexicographically.
I have searched and can't find any solutions. Here is what I have already tried:
temp = {'c' : 3, 'b': 3, 'aa' : 2, 'a' : 2}
results = []
for key, value in temp.items():
results.append([key, value])
results.sort(key = operator.itemgetter(1,0), reverse = True)
for result in results:
print(result)
This doesn't work though it results in this:
c
b
aa
a
The output should be:
b
c
a
aa
I appreciate any help!
(Note: using Python 3)
>>> d = {'c': 3, 'b': 3, 'aa': 2, 'a': 2}
>>> sorted(d, key=lambda key: (-d[key], key))
['b', 'c', 'a', 'aa']
- was used to make the value make it ordered descendingly by the value.

How to get all the keys with the same highest value?

If I have a dictionary with their corresponding frequency values:
numbers = {'a': 1, 'b': 4, 'c': 1, 'd': 3, 'e': 3}
To find the highest, what I know is:
mode = max(numbers, key=numbers.get)
print mode
and that prints:
b
But if I have:
numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
and apply the 'max' function above, the output is:
d
What I need is:
d,e
Or something similar, displaying both keys.
numbers = {'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3}
max_value = max(numbers.values())
[k for k,v in numbers.items() if v == max_value]
prints
['e', 'd']
what it does is, loop over all entries via .items and then check if the value is the maximum and if so add the key to a list.
numbers = {'a': 1, 'b': 4, 'c': 1, 'd':4 , 'e': 3}
mx_tuple = max(numbers.items(),key = lambda x:x[1]) #max function will return a (key,value) tuple of the maximum value from the dictionary
max_list =[i[0] for i in numbers.items() if i[1]==mx_tuple[1]] #my_tuple[1] indicates maximum dictionary items value
print(max_list)
This code will work in O(n). O(n) in finding maximum value and O(n) in the list comprehension. So overall it will remain O(n).
Note : O(2n) is equivalent to O(n).
The collections.Counter object is useful for this as well. It gives you a .most_common() method which will given you the keys and counts of all available values:
from collections import Counter
numbers = Counter({'a': 1, 'b': 0, 'c': 1, 'd': 3, 'e': 3})
values = list(numbers.values())
max_value = max(values)
count = values.count(max_value)
numbers.most_common(n=count)
You can use the .items() property and sort after a tuple of count, key - on similar counts the key will decide:
d = ['a','b','c','b','c','d','c','d','e','d','b']
from collections import Counter
get_data = Counter(d)
# sort by count, then key
maxmax = sorted(get_data.items(), key=lambda a: (a[1],a[0]) )
for elem in maxmax:
if elem[1] == maxmax[0][1]:
print (elem)
Output:
('a', 1)
('e', 1) # the last one is the one with "highest" key
To get the "highest" key, use maxmax[-1].

Performing circular shif on values in a dictionary

I have to construct a large dictionary which looks something like this
{'A' : {'A' : 1, 'B' : 0, 'C' : 0},
'B' : {'A' : 0, 'B' : 1, 'C' : 0}}
............................
Each inner dictionary is shifted by one position. Is there a way I can automate this process.
I can loop and use np.roll() function if it were ndarray so I am wondering if there's something similiar I could do with dictionaries.
You can use collections.deque for fast dictionary values (list) shifting (deque rotate function) but there is no specific function for dictionary, you should make it yourself, for example:
# shift dct (dict) values by n to right if n is positive
# and to left if n is negative; returns new dictionary
def dict_roll(dct, n):
shift_values = deque(dct.values())
shift_values.rotate(n)
return dict(zip(dct.keys(), shift_values))
Demo:
>>> d = {'A': {'A': 1, 'C': 0, 'B': 0}, 'B': {'A': 0, 'C': 0, 'B': 1}}
>>> for k in d:
... d[k] = dict_roll(d[k], 1)
...
>>> d
{'A': {'A': 0, 'C': 1, 'B': 0}, 'B': {'A': 1, 'C': 0, 'B': 0}}
>>> for k in d:
... d[k] = dict_roll(d[k], 1)
...
>>> d
{'A': {'A': 0, 'C': 0, 'B': 1}, 'B': {'A': 0, 'C': 1, 'B': 0}}
And another solution.
Solution 1:
out = dict()
syms = ['A', 'B', 'C']
for sym_outer in syms:
inner_dict = dict()
for sym_inner in syms:
inner_dict[sym_inner] = 0 if sym_inner != sym_outer else 1
out[sym_outer] = inner_dict
Solution 2:
This is a partial solution, but you get out['A']['A'] == 1 and out['A']['B'] == 0.
from collections import defaultdict
out = defaultdict(lambda: defaultdict(int))
for sym in ['A', 'B', 'C']:
out[sym][sym] = 1
This will create your string in r:
import string
r = {}
a = [1] + [0] * 25
for i in string.ascii_uppercase:
r[i] = dict(zip(string.ascii_uppercase,a))
a = a[-1:] + a[:-1]
print r
Bonus one-liner
If you are using Python 2.7+ or Python 3, then you can get a one-liner using dictionary comprehensions:
import string
{i:{j:1 if i==j else 0 for j in string.ascii_uppercase} for i in string.ascii_uppercase}

Get values in Python dictionary from list of keys

If I have a dictionary
d = {'a':1, 'b':2 , 'c': 3}
with d['a'] or d.get('a') I get 1.
How can I get the values in the dictionary from a list of keys?
Something like
d[['a','b']]
Use list comprehension:
>>> d = {'a':1, 'b':2 , 'c': 3}
>>> [d[k] for k in ['a','b']]
[1, 2]
I would use map:
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> map(d.get, ['a','b'])
[1, 2]
Alternatively to a list in this case you could use a string. Like so:
map({'a':1, 'b':2 , 'c': 3}.get,"abc")

Categories

Resources