I have a dictionary defined as:
letters = {'a': 2, 'b': 1, 'c': 5}
I want to add values to this dictionary based on two lists: one which contains the keys and another which contains the values.
key_list = [a, c]
value_list = [2, 5]
This should give the output:
{a: 4, b: 1, c: 10}
Any ideas on how I can accomplish this? I am new to working with the dictionary structure so I apologise if this is extremely simple.
Thanks.
You can zip the two lists and then add to the dictionary as so;
letters = {'a': 2, 'b': 1, 'c': 5}
key_list = ['a', 'c']
value_list = [2, 5]
for k,v in zip(key_list, value_list):
letters[k] = letters.get(k, 0) + v
Using the dictionary's get() method as above allows you to add letters that aren't already in the dictionary.
for i in range(len(key_list)):
letters[key_list[i]] += value_list[i]
You can simply add or modify values from a dictionary using the key
For example:
letters = {'a': 2, 'b':1 , 'c': 5}
letters['a'] += 2
letters['c'] += 5
print(letters)
output = {'a': 4, 'b': 1, 'c': 10}
How can I iterate over only X number of dictionary items? I can do it using the following bulky way, but I am sure Python allows a more elegant way.
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
x = 0
for key in d:
if x == 3:
break
print key
x += 1
If you want a random sample of X values from a dictionary you can use random.sample on the dictionary's keys:
from random import sample
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
X = 3
for key in sample(d, X):
print key, d[key]
And get output for example:
e 5
c 3
b 2
This question already has answers here:
Comparing two dictionaries and checking how many (key, value) pairs are equal
(28 answers)
Closed 4 years ago.
This seems trivial, but I cannot find a built-in or simple way to determine if two dictionaries are equal.
What I want is:
a = {'foo': 1, 'bar': 2}
b = {'foo': 1, 'bar': 2}
c = {'bar': 2, 'foo': 1}
d = {'foo': 2, 'bar': 1}
e = {'foo': 1, 'bar': 2, 'baz':3}
f = {'foo': 1}
equal(a, b) # True
equal(a, c) # True - order does not matter
equal(a, d) # False - values do not match
equal(a, e) # False - e has additional elements
equal(a, f) # False - a has additional elements
I could make a short looping script, but I cannot imagine that mine is such a unique use case.
== works
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e
True
I hope the above example helps you.
The good old == statement works.
I know we use enumerate for iterating a list but I tried it on a dictionary and it didn't give an error.
CODE:
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, key in enumerate(enumm):
print(i, key)
OUTPUT:
0 0
1 1
2 2
3 4
4 5
5 6
6 7
Can someone please explain the output?
On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.
The normal case you enumerate the keys of the dictionary:
example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}
for i, k in enumerate(example_dict):
print(i, k)
Which outputs:
0 1
1 2
2 3
3 4
But if you want to enumerate through both keys and values this is the way:
for i, (k, v) in enumerate(example_dict.items()):
print(i, k, v)
Which outputs:
0 1 a
1 2 b
2 3 c
3 4 d
The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():
for k, v in enumm.items():
print(k, v)
And the output should look like:
0 1
1 2
2 3
4 4
5 5
6 6
7 7
Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:
for index, (key, value) in enumerate(your_dict.items()):
print(index, key, value)
dict1={'a':1, 'b':'banana'}
To list the dictionary in Python 2.x:
for k,v in dict1.iteritems():
print k,v
In Python 3.x use:
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
Finally, as others have indicated, if you want a running index, you can have that too:
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.
enumerate() when working on list actually gives the index and the value of the items inside the list.
For example:
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
print(i, j)
gives
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
where the first column denotes the index of the item and 2nd column denotes the items itself.
In a dictionary
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
print(i, j)
it gives the output
0 0
1 1
2 2
3 4
4 5
5 6
6 7
where the first column gives the index of the key:value pairs and the second column denotes the keys of the dictionary enumm.
So if you want the first column to be the keys and second columns as values, better try out dict.iteritems()(Python 2) or dict.items() (Python 3)
for i, j in enumm.items():
print(i, j)
output
0 1
1 2
2 3
4 4
5 5
6 6
7 7
Voila
Since you are using enumerate hence your i is actually the index of the key rather than the key itself.
So, you are getting 3 in the first column of the row 3 4even though there is no key 3.
enumerate iterates through a data structure(be it list or a dictionary) while also providing the current iteration number.
Hence, the columns here are the iteration number followed by the key in dictionary enum
Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.
Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
The order of the keys is determined by the implementation code and you cannot expect some specific order:
Keys and values are iterated over in an arbitrary order which is
non-random, varies across Python implementations, and depends on the
dictionary’s history of insertions and deletions. If keys, values and
items views are iterated over with no intervening modifications to the
dictionary, the order of items will directly correspond.
That's why you see the indices 0 to 7 in the first column. They are produced by enumerate and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.
That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.
Python3:
One solution:
enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))
Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7
An another example:
d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
2 : {'a': 10, 'b' : 20, 'c' : 30}
}
for i, k in enumerate(d):
print("{}) key={}, value={}".format(i, k, d[k])
Output:
0) key=1, value={'a': 1, 'b': 2, 'c': 3}
1) key=2, value={'a': 10, 'b': 20, 'c': 30}
You may find it useful to include index inside key:
d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}
Output:
{(0, 'a'): True, (1, 'b'): False}
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
print("List of enumerated d= ", list(enumerate(d.items())))
output:
List of enumerated d= [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
I am trying to get it so that this code:
from collections import Counter
a = input('Votes: ')
a = a.split(',')
count = Counter(a)
print (count)
When I input something like this:
One,One,Two,Two,Three,Four,Five,Five
prints this:
One: 2
Two: 2
Three: 1
Four: 1
Five:2
instead of this:
Counter({'One': 2, 'Two': 2, 'Five': 2, 'Three': 1, 'Four': 1})
Loop over the Counter.most_common() output:
for key, c in count.most_common():
print("{}: {}".format(key, c))
The most_common() method gives you the items in sorted order, from most to least common:
If you need to order them by their 'came first' ordering in a (so One before Two simply because One was mentioned first) then sort them by their string index with str.index().
for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
print("{}: {}".format(key, c))
If you needed to order them by the ordinal interpretation of the numbers, use a dictionary translating words to digits:
numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} # expand as needed
for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
print("{}: {}".format(key, c))
Demo:
>>> from collections import Counter
>>> a = 'One,One,Two,Two,Three,Four,Five,Five'.split(',')
>>> count = Counter(a)
>>> for key, c in count.most_common():
... print("{}: {}".format(key, c))
...
Five: 2
Two: 2
One: 2
Three: 1
Four: 1
>>> for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
... print("{}: {}".format(key, c))
...
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
>>> numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> for key, c in sorted(count.items(), key=lambda i: numbers[i[0].lower()]):
... print("{}: {}".format(key, c))
...
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
from collections import Counter
a = input('Votes: ')
a = a.split(',')
count = Counter(a)
for key in sorted(set(a),key=lambda x: a.index(x)):
print ("{}: {}".format(key,count[key]))
In [13]: for key in sorted(set(a),key=lambda x: a.index(x)):
....: print ("{}: {}".format(key,count[key]))
....:
One: 2
Two: 2
Three: 1
Four: 1
Five: 2
Make a set to remove the duplicates and use sorted with a lambda to sort based on the index of the corresponding value in the a list which matches the input order
One liner, sorted:
a = ['One','One','Two','Two','Three','Four','Five','Five']
counts = Counter(a)
print('\n'.join('{}: {}'.format(*x) for x in sorted(counts.items(), key=lambda x: a.index(x[0]))))