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
Related
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]))
I have a list of tuples:
[ (a,1), (a,2), (b,1), (b,3) ]
I want to get the sum of both the a and b values. The results should be in this format:
[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ]
How can I do this?
from itertools import groupby
[{'key': k, 'value': sum(v for _,v in g)} for k, g in groupby(sorted(lst), key = lambda x: x[0])]
# [{'key': 'a', 'value': 3}, {'key': 'b', 'value': 4}]
from collections import defaultdict
lst = [("a", 1), ("a", 2), ("b", 1), ("b", 3)]
out = defaultdict(list)
[out[v[0]].append(v[1]) for v in lst]
out = [{"key": k, "value": sum(v)} for k, v in out.iteritems()]
print out
You can use collections.Counter to create a multiset from the initial list and then modify the result to match your case:
from collections import Counter
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
part = sum((Counter({i[0]: i[1]}) for i in lst), Counter())
# Counter({'b': 4, 'a': 3})
final = [{'key': k, 'value': v} for k, v in part.items()]
# [{'key': 'b', 'value': 4}, {'key': 'a', 'value': 3}]
Very similar to answers given already. Little bit longer, but easier to read, IMHO.
from collections import defaultdict
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
dd = defaultdict(int)
for name, value in lst:
dd[name] += value
final = [{'key': k, 'value': v} for k, v in dd.items()]
(last line copied from Moses Koledoye's answer)
from collections import Counter
a = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
c = Counter()
for tup in a:
c = c + Counter(dict([tup]))
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}
In Python 2.7, suppose I have a list with 2 member sets like this
d = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
What is the easiest way in python to turn it into a dictionary like this:
d = {1 : 'value1', 2 : 'value2', 3 : 'value3'}
Or, the opposite, like this?
d = {'value1' : 1, 'value2': 2, 'value3' : 3}
Thanks
The dict constructor can take a sequence. so...
dict([(1, 'value1'), (2, 'value2'), (3, 'value3')])
and the reverse is best done with a dictionary comprehension
{k: v for v,k in [(1, 'value1'), (2, 'value2'), (3, 'value3')]}
If your list is in the form of a list of tuples then you can simply use dict().
In [5]: dict([(1, 'value1'), (2, 'value2'), (3, 'value3')])
Out[5]: {1: 'value1', 2: 'value2', 3: 'value3'}
A dictionary comprehension can be used to construct the reversed dictionary:
In [13]: { v : k for (k,v) in [(1, 'value1'), (2, 'value2'), (3, 'value3')] }
Out[13]: {'value1': 1, 'value2': 2, 'value3': 3}
>>> lis = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
Use dict() for the first one:
>>> dict(lis)
{1: 'value1', 2: 'value2', 3: 'value3'}
And a dict comprehension for the second one:
>>> {v:k for k,v in lis}
{'value3': 3, 'value2': 2, 'value1': 1}
dict() converts an iterable into a dict:
>>> print dict.__doc__
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
lst = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
To turn it to dict, just do
dict(lst)
to reverse it, you can do
dict((b,a) for a,b in lst)
dict(my_list) should probably do the trick. Also, I think you have a list of tuples, not sets.
>>> d = [(1, 'value1'), (2, 'value2'), (3, 'value3')]
>>> dict(d)
{1: 'value1', 2: 'value2', 3: 'value3'}
>>> dict(map(reversed, d))
{'value3': 3, 'value2': 2, 'value1': 1}
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