I have sorted the dictionary using sorted() method and it returns a list of key-value tuples as:-
MyDict = {'a': 8, 'b': 4, 'c': 3, 'd': 1, 'e': 0, 'f': 0, 'g': 1, 'h' :1}
data = sorted(MyDict.items(), key=lambda x: x[1], reverse=True)
print(data)
Output:-
[('a', 8), ('b', 4), ('c', 3), ('d', 1), ('g', 1), ('h', 1), ('e', 0), ('f', 0)]
Now, I want to iterate over it using for loop and print the keys as well as values that are divisible by k (k can me any integer number). This seems a basic question, but I am a beginner and it seems tricky to me. Help would be really appreciated.
k = 4
data = [('a', 8), ('b', 4), ('c', 3), ('d', 1), ('g', 1), ('h', 1), ('e', 0), ('f', 0)]
for item in data:
if item[1] % k == 0:
print('Key = %s, Value = %.i' % (item[0], item[1]))
Output:
Key = a, Value = 8
Key = b, Value = 4
Key = e, Value = 0
Key = f, Value = 0
Try the following:
num = 1
for key, value in data:
if value % num == 0:
print("Key: {0} Value: {1}".format(key, value))
you don't need to convert the dictionary to list of tuples for doing that.
Try this :
MyDict = {'a': 8, 'b': 4, 'c': 3, 'd': 1, 'e': 0, 'f': 0, 'g': 1, 'h' :1}
k = 2 # it can be any value as you say
for key,val in MyDict.iteritems():
if val%k ==0:
print("Key - {0} and value - {1}".format(key,val))
If you still need to convert the given dictionary to list of tuples and then use it, here is how you can do it.
MyDict = {'a': 8, 'b': 4, 'c': 3, 'd': 1, 'e': 0, 'f': 0, 'g': 1, 'h' :1}
data = sorted(MyDict.items(), key=lambda x: x[1], reverse=True)
k = 2 # any int value you want.
for item in data:
if item[1]%k == 0:
print("Key - {0} and value - {1}".format(item[0],item[1]))
Related
List looks like this having ascii character and number value, I want to count occurrence of each of ASCII character for 0, 1 and 2
So for A {0=10, 1=2, 2 =12} likewise
[('P', 0),
('S', 2),
('R', 1),
('O', 1),
('J', 1),
('E', 1),
('C', 1),
('T', 1),
('G', 1),
('U', 1),
('T', 1),
('E', 1),
('N', 1)]
I have tried
char_freq = {c:[0,0,0] for c in string.ascii_uppercase}
also
for i in range(3):
for x,i in a:
print(x,i)
I want to count X for i where X is [A-Z]
It should give me result like
Character | 0 | 1 | 2
A 10 5 4
although you don't supply enough example data to actually achieve your desired output.. i think this is what you're looking for:
from collections import Counter
import pandas as pd
l = [('P', 0),
('S', 2),
('R', 1),
('O', 1),
('J', 1),
('E', 1),
('C', 1),
('T', 1),
('G', 1),
('U', 1),
('T', 1),
('E', 1),
('N', 1)]
df = pd.DataFrame(l)
counts = df.groupby(0)[1].agg(Counter)
returns:
C {1: 1}
E {1: 2}
G {1: 1}
J {1: 1}
N {1: 1}
O {1: 1}
P {0: 1}
R {1: 1}
S {2: 1}
T {1: 2}
U {1: 1}
this will give you each ASCII character, along with each unique number, and how many occurrences of each number
from collections import Counter
l = [('A', 1),
('A', 1),
('A', 2),
('A', 2),
('B', 1),
('B', 2),
('B', 3),
('B', 4)]
data = {}
for k,v in l:
data[k] = [v] if k not in data else data[k] + [v]
char_freq = {k: dict(Counter(v)) for k, v in data.items()}
print(char_freq)
Outputs:
{'A': {1: 2, 2: 2}, 'B': {1: 1, 2: 1, 3: 1, 4: 1}}
your code looks fine you just have to make a small change to the char_freq variable to get the expected result:
char_freq = {c: {0: 0, 1: 0, 2: 0} for c in string.ascii_uppercase}
for x, i in a:
char_freq[x][i] += 1
to avoid having all the alphabet in your char_freq you could use only the necessary characters:
char_freq = {c: {0: 0, 1: 0, 2: 0} for c in {t[0] for t in a}}
for x, i in a:
char_freq[x][i] += 1
output:
{'O': {0: 0, 1: 1, 2: 0},
'T': {0: 0, 1: 2, 2: 0},
'N': {0: 0, 1: 1, 2: 0},
'G': {0: 0, 1: 1, 2: 0},
'U': {0: 0, 1: 1, 2: 0},
'E': {0: 0, 1: 2, 2: 0},
'J': {0: 0, 1: 1, 2: 0},
'R': {0: 0, 1: 1, 2: 0},
'C': {0: 0, 1: 1, 2: 0},
'S': {0: 0, 1: 0, 2: 1},
'P': {0: 1, 1: 0, 2: 0}}
I have a dict of keys and values. I need to compare the values of all the keys if there are the same values in the dict and then return the keys, which have the same values.
b = {(1, 1): '4', (2, 1): '4',(3,1):'8',(4,2):'9',(2,4):'10'}
p = dict(zip(b.values(),b.keys()))
The output I'm getting:
{'4': (2, 1), '8': (3, 1), '9': (4, 2), '10': (2, 4)}
Expected output:
{(1, 1): '4', (2, 1): '4'}
A single liner using dict comprehension :
>>> {k:v for k, v in b.items() if list(b.values()).count(v) > 1}
Here to determine if other values also contain the same, we check for the count to be greater than one.
#driver values :
IN : b = {(1, 1): '4', (2, 1): '4',(3,1):'8',(4,2):'9',(2,4):'10'}
OUT : {(1, 1): '4', (2, 1): '4'}
If I have a dictionary like:
{'a': 1, 'b': 2, 'c': 3}
How can I convert it to this?
[('a', 1), ('b', 2), ('c', 3)]
And how can I convert it to this?
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
For Python 3.6 and later, the order of the list is what you would expect.
In Python 2, you don't need list.
since no one else did, I'll add py3k versions:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]
You can use list comprehensions.
[(k,v) for k,v in a.iteritems()]
will get you [ ('a', 1), ('b', 2), ('c', 3) ] and
[(v,k) for k,v in a.iteritems()]
the other example.
Read more about list comprehensions if you like, it's very interesting what you can do with them.
Create a list of namedtuples
It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:
d = {'John':5, 'Alex':10, 'Richard': 7}
You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:
>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
How to do this:
list in random order or keeping order of collections.OrderedDict:
import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
in order, sorted by value ('score'):
import collections
Player = collections.namedtuple('Player', 'score name')
sorted with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorted with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
[(k,v) for (k,v) in d.iteritems()]
and
[(v,k) for (k,v) in d.iteritems()]
What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>>
These are the breaking changes from Python 3.x and Python 2.x
For Python3.x use
dictlist = []
for key, value in dict.items():
temp = [key,value]
dictlist.append(temp)
For Python 2.7 use
dictlist = []
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
>>> a={ 'a': 1, 'b': 2, 'c': 3 }
>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]
>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]
By keys() and values() methods of dictionary and zip.
zip will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
A alternative one would be
list(dictionary.items()) # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys())) # list of (value, key) tuples
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
k = (i,d[i])
list.append(k)
print list
Python3 dict.values() not return a list. This is the example
mydict = {
"a": {"a1": 1, "a2": 2},
"b": {"b1": 11, "b2": 22}
}
print(mydict.values())
> output: dict_values([{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}])
print(type(mydict.values()))
> output: <class 'dict_values'>
print(list(mydict.values()))
> output: [{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}]
print(type(list(mydict.values())))
> output: <class 'list'>
x = {'a': 1, 'b': 2, 'c': 4, 'd':3}
sorted(map(lambda x : (x[1],x[0]),x.items()),key=lambda x : x[0])
Lets break the above code into steps
step1 = map(lambda x : (x[1],x[0]),x.items())
x[1] : Value
x[0] : Key
Step1 will create a list of tuples containing pairs in the form of (value,key) e.g. (4,'c')
step2 = sorted(step1,key=lambda x : x[0])
Step2 take the input of from Step 1 and sort using the 1st value of the tuple
I used the sample from the documentation:
>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]
How can I make the result to be:
{ 'a': 5, 'r' :2 , 'b' :2}
supposing that we want to keep the Counter().most_common() code?
dict will do this easily:
>>> dict(Counter('abracadabra').most_common(3))
{'a': 5, 'r': 2, 'b': 2}
>>>
For further reference, here is part of what is returned by help(dict):
dict(iterable) -> new dictionary initialized as if via:
| d = {}
| for k, v in iterable:
| d[k] = v
The easiest way is to simply use dict()
dict(Counter('abracadabra').most_common(3))
Output:
{'a': 5, 'r': 2, 'b': 2}
If I have a dictionary like:
{'a': 1, 'b': 2, 'c': 3}
How can I convert it to this?
[('a', 1), ('b', 2), ('c', 3)]
And how can I convert it to this?
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
For Python 3.6 and later, the order of the list is what you would expect.
In Python 2, you don't need list.
since no one else did, I'll add py3k versions:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v, k) for k, v in d.items()]
[(1, 'a'), (3, 'c'), (2, 'b')]
You can use list comprehensions.
[(k,v) for k,v in a.iteritems()]
will get you [ ('a', 1), ('b', 2), ('c', 3) ] and
[(v,k) for k,v in a.iteritems()]
the other example.
Read more about list comprehensions if you like, it's very interesting what you can do with them.
Create a list of namedtuples
It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:
d = {'John':5, 'Alex':10, 'Richard': 7}
You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:
>>> player = best[0]
>>> player.name
'Alex'
>>> player.score
10
How to do this:
list in random order or keeping order of collections.OrderedDict:
import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())
in order, sorted by value ('score'):
import collections
Player = collections.namedtuple('Player', 'score name')
sorted with lowest score first:
worst = sorted(Player(v,k) for (k,v) in d.items())
sorted with highest score first:
best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)
[(k,v) for (k,v) in d.iteritems()]
and
[(v,k) for (k,v) in d.iteritems()]
What you want is dict's items() and iteritems() methods. items returns a list of (key,value) tuples. Since tuples are immutable, they can't be reversed. Thus, you have to iterate the items and create new tuples to get the reversed (value,key) tuples. For iteration, iteritems is preferable since it uses a generator to produce the (key,value) tuples rather than having to keep the entire list in memory.
Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = { 'a': 1, 'b': 2, 'c': 3 }
>>> a.items()
[('a', 1), ('c', 3), ('b', 2)]
>>> [(v,k) for (k,v) in a.iteritems()]
[(1, 'a'), (3, 'c'), (2, 'b')]
>>>
These are the breaking changes from Python 3.x and Python 2.x
For Python3.x use
dictlist = []
for key, value in dict.items():
temp = [key,value]
dictlist.append(temp)
For Python 2.7 use
dictlist = []
for key, value in dict.iteritems():
temp = [key,value]
dictlist.append(temp)
>>> a={ 'a': 1, 'b': 2, 'c': 3 }
>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]
>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]
By keys() and values() methods of dictionary and zip.
zip will return a list of tuples which acts like an ordered dictionary.
Demo:
>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]
A alternative one would be
list(dictionary.items()) # list of (key, value) tuples
list(zip(dictionary.values(), dictionary.keys())) # list of (value, key) tuples
d = {'John':5, 'Alex':10, 'Richard': 7}
list = []
for i in d:
k = (i,d[i])
list.append(k)
print list
Python3 dict.values() not return a list. This is the example
mydict = {
"a": {"a1": 1, "a2": 2},
"b": {"b1": 11, "b2": 22}
}
print(mydict.values())
> output: dict_values([{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}])
print(type(mydict.values()))
> output: <class 'dict_values'>
print(list(mydict.values()))
> output: [{'a1': 1, 'a2': 2}, {'b1': 11, 'b2': 22}]
print(type(list(mydict.values())))
> output: <class 'list'>
x = {'a': 1, 'b': 2, 'c': 4, 'd':3}
sorted(map(lambda x : (x[1],x[0]),x.items()),key=lambda x : x[0])
Lets break the above code into steps
step1 = map(lambda x : (x[1],x[0]),x.items())
x[1] : Value
x[0] : Key
Step1 will create a list of tuples containing pairs in the form of (value,key) e.g. (4,'c')
step2 = sorted(step1,key=lambda x : x[0])
Step2 take the input of from Step 1 and sort using the 1st value of the tuple