I have a dictionary like such:
aDict = {'a': [1,2,3],
'b': [2,3,4],
'c': [3,3,6], ...}
How would I create a list that stores the maximum values at each index, (0,1,2).
Thanks!
If I understand right, you want something like this:
>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aList = [max(aDict[k]) for k in sorted(aDict.keys())]
>>> print aList
[3, 4, 6]
Or maybe this:
>>> aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
>>> aDict2 = dict((k, max(aDict[k])) for k in aDict.keys())
>>> print aDict2
{'a': 3, 'c': 6, 'b': 4}
Related
There is this list of string that I need to use to create a nested dictionary with some values ['C/A', 'C/B/A', 'C/B/B']
The output will be in the format {'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}
I've tried to use the below code to create the nested dictionary and update the value, but instead I get {'C': {'A': [1, 2, 3], 'C': {'B': {'A': [1, 2, 3], 'C': {'B': {'B': [1, 2, 3]}}}}}} as the output which is not the correct format. I'm still trying to figure out a way. any ideas?
s = ['C/A', 'C/B/A', 'C/B/B']
new = current = dict()
for each in s:
lst = each.split('/')
for i in range(len(lst)):
current[lst[i]] = dict()
if i != len(lst)-1:
current = current[lst[i]]
else:
current[lst[i]] = [1,2,3]
print(new)
You can create a custom Tree class:
class Tree(dict):
'''
Create arbitrarily nested dicts.
>>> t = Tree()
>>> t[1][2][3] = 4
>>> t
{1: {2: {3: 4}}}
>>> t.set_nested_item('a', 'b', 'c', value=5)
>>> t
{1: {2: {3: 4}}, 'a': {'b': {'c': 5}}}
'''
def __missing__(self, key):
self[key] = type(self)()
return self[key]
def set_nested_item(self, *keys, value):
head, *rest = keys
if not rest:
self[head] = value
else:
self[head].set_nested_item(*rest, value=value)
>>> s = ['C/A', 'C/B/A', 'C/B/B']
>>> output = Tree()
>>> default = [1, 2, 3]
>>> for item in s:
... output.set_nested_item(*item.split('/'), value=list(default))
>>> output
{'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}
You do not need numpy for this problem, but you may want to use recursion. Here is a recursive function add that adds a list of string keys lst and eventually a list of numbers to the dictionary d:
def add(lst, d):
key = lst[0]
if len(lst) == 1: # if the list has only 1 element
d[key] = [1, 2, 3] # That element is the last key
return
if key not in d: # Haven't seen that key before
d[key] = dict()
add(lst[1:], d[key]) # The recursive part
To use the function, create a new dictionary and apply the function to each splitter string:
d = dict()
for each in s:
add(each.split("/"), d)
# d
# {'C': {'A': [1, 2, 3], 'B': {'A': [1, 2, 3], 'B': [1, 2, 3]}}}
I know about few of the questions answered here on SO about dict(list) i.e.
l = [['a',1] ['b',2]]
and do dict(l) then we get:
{'a': 1, 'b': 2}
But how to make a list with 2 elements
l = ['a',1]
become a dictionary such as:
{'a':1}
using the dict function?
dict expects an iterable of two-item iterables, so you will need to put l in a list:
>>> l = ['a',1]
>>> dict([l])
{'a': 1}
>>>
Note that you could also use a tuple:
>>> l = ['a',1]
>>> dict((l,))
{'a': 1}
>>>
This works for multiple elements in the list
>>> l = ['a',1,'b',2]
>>> i = [(l[i],l[i+1]) for i in range(0,len(l),2)]
>>> dict(i)
{'a': 1, 'b': 2}
For one element, dict([l]) would work. For multiple key/value pairs in a flattened list, you could use zip():
In [5]: l = ['a', 1, 'b', 2]
In [6]: dict(zip(l[::2], l[1::2]))
Out[6]: {'a': 1, 'b': 2}
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.
This question already has answers here:
How to merge dicts, collecting values from matching keys?
(17 answers)
Closed 12 days ago.
Given n dictionaries, write a function that will return a unique dictionary with a list of values for duplicate keys.
Example:
d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'b': 4}
d3 = {'a': 5, 'd': 6}
result:
>>> newdict
{'c': 3, 'd': 6, 'a': [1, 5], 'b': [2, 4]}
My code so far:
>>> def merge_dicts(*dicts):
... x = []
... for item in dicts:
... x.append(item)
... return x
...
>>> merge_dicts(d1, d2, d3)
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}, {'a': 5, 'd': 6}]
What would be the best way to produce a new dictionary that yields a list of values for those duplicate keys?
Python provides a simple and fast solution to this: the defaultdict in the collections module. From the examples in the documentation:
Using list as the default_factory, it is easy to group a sequence of
key-value pairs into a dictionary of lists:
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', 1), ('yellow', [1, 3])]
When each key is encountered for the first time, it is not already in
the mapping; so an entry is automatically created using the
default_factory function which returns an empty list. The
list.append() operation then attaches the value to the new list. When
keys are encountered again, the look-up proceeds normally (returning
the list for that key) and the list.append() operation adds another
value to the list.
In your case, that would be roughly:
import collections
def merge_dicts(*dicts):
res = collections.defaultdict(list)
for d in dicts:
for k, v in d.iteritems():
res[k].append(v)
return res
>>> merge_dicts(d1, d2, d3)
defaultdict(<type 'list'>, {'a': [1, 5], 'c': [3], 'b': [2, 4], 'd': [6]})
def merge_dicts(*dicts):
d = {}
for dict in dicts:
for key in dict:
try:
d[key].append(dict[key])
except KeyError:
d[key] = [dict[key]]
return d
This retuns:
{'a': [1, 5], 'b': [2, 4], 'c': [3], 'd': [6]}
There is a slight difference to the question. Here all dictionary values are lists. If that is not to be desired for lists of length 1, then add:
for key in d:
if len(d[key]) == 1:
d[key] = d[key][0]
before the return d statement. However, I cannot really imagine when you would want to remove the list. (Consider the situation where you have lists as values; then removing the list around the items leads to ambiguous situations.)
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")