Let's assume i start with this dictionary:
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,1], [1,7,9], [6,2,3]],
'c': [['a'], [4,5]],
}
How can i append values to 'a' yet be able to add a new key if i needed to let's say 'd' what i tried is
plus_min_dict = {}
plus_min_dict[key] = reference_dataset[key][line_number]
but it only gave one value per key apparently = destroyed the previous value, i want to update or append yet still be able to create a new key if it doesn't exist
Edit: To clarify let's assume this is my initial dictionary:
mydict = {
'a': [[2,4]],}
i do other calculations with another dictionary let's assume it's :
second_dict = {
'a': [ [5,6]],
'b': [[1,1], [1,7,9]],
'c': [['a'], [4,5]],
}
these calculations showed me that i have interest in [5,6] of 'a' and [1,7,9] of 'b' so i want mydict to become:
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,7,9]],
}
If I understand well your question, you want to append a new value to your dictionary if the key already exists. If so, I would use a defaultdict for a simple reason. With a defaultdict you can use the method += to create (if does not exist) or add (if exist) an element :
from collections import defaultdict
# Your dictionaries
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,1], [1,7,9], [6,2,3]],
'c': [['a'], [4,5]],
}
plus_min_dict = {'a': [[3,3]]}
# d is a DefaultDict containing mydict values
d=defaultdict(list,mydict)
# d_new is a DefaultDict containing plus_min_dict dict
d_new = defaultdict(list, plus_min_dict)
# Add all key,values of d in d_new
for k, v in d.items():
d_new[k] += d[k]
print(d_new)
Results :
defaultdict(<class 'list'>, {'c': [['a'], [4, 5]], 'a': [[3, 3], [2, 4], [5, 6]], 'b': [[1, 1], [1, 7, 9], [6, 2, 3]]})
Use an if else loop
mydict = {'a': [[2,4]],}
second_dict = {
'a': [ [5,6]],
'b': [[1,1], [1,7,9]],
'c': [['a'], [4,5]]}
missing_values = {
'a': [5,6],
'b': [1,7,9]}
for key, value in missing_values.items():
if key in mydict:
mydict[key ].append(value)
else:
mydict[key ] = [value]
print(mydict)
Result:
{'a': [[2, 4], [5, 6]], 'b': [[1, 7, 9]]}
To append an item into 'a', you can do this:
mydict['a'] += ['test_item']
Or:
mydict['a'].append('test_item')
You can just append:
mydict = {
'a': [[2,4], [5,6]],
'b': [[1,1], [1,7,9], [6,2,3]],
'c': [['a'], [4,5]],
}
mydict['a'].append([7,8])
mydict['d'] = [0,1]
print(mydict)
Related
I am trying to calculate a “score” for each key in a dictionary. The values for the key values are in a different list. Simplified example:
I have:
Key_values = ['a': 1, 'b': 2, 'c': 3, 'd': 4]
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}
I want:
Scores = ['player1': 8, 'player2': 7]
You can create it using a dict comprehension:
Key_values = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}
scores = {player: sum(Key_values[mark] for mark in marks) for player, marks in My_dict.items()}
print(scores)
# {'player1': 8, 'player2': 7}
Try this:
>>> Key_values = {"a" : 1, "b" : 2, "c": 3, "d" : 4}
>>> My_dict = {"player1":["a", "d", "c"], "player2":["b", "a", "d"]}
>>> Scores= {k: sum(Key_values.get(v_el, 0) for v_el in v) for k,v in My_dict.items()}
>>> Scores
{'player1': 8, 'player2': 7}
try this:
score = {}
key_values = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
my_dict = {'player1': ['a', 'c', 'd'], 'player2': ['b', 'a', 'd']}
scr = 0
for i in my_dict.keys(): # to get all keys from my_dict
for j in my_dict[i]: # iterate the value list for key.
scr += key_values[j]
score[i] = scr
scr = 0
print(score)
Try this: (Updated the syntax in question. key-value pairs are enclosed within curley braces.)
Key_values = {‘a’ : 1, ‘b’ : 2, ‘c’: 3, ‘d’ : 4}
My_dict = {‘player1’=[‘a’, ‘d’, ‘c’], ‘player2’=[‘b’, ‘a’, ‘d’]}
Scores = dict()
for key, value in My_dict.items():
total = 0
for val in value:
total += Key_values[val]
Scores[key] = total
print(Scores)
# {‘player1’ : 8, ‘player2: 7}
You can do it with appropriate dict methods and map, should be the fastest among the ones already posted.
Key_values = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
My_dict = {'player1': ['a', 'd', 'c'], 'player2': ['b', 'a', 'd']}
new_dict = {key:sum(map(Key_values.get,My_dict[key])) for key in My_dict}
print(new_dict)
Output:
{'player1': 8, 'player2': 7}
I have a existing dict that maps single values to lists.
I want to reverse this dictionary and map from every list entry on the original key.
The list entries are unique.
Given:
dict { 1: ['a', 'b'], 2: ['c'] }
Result:
dict { 'a' : 1, 'b' : 1, 'c' : 2 }
How can this be done?
Here's an option
new_dict = {v: k for k, l in d.items() for v in l}
{'a': 1, 'b': 1, 'c': 2}
You can use a list comprehension to produce a tuple with the key-value pair, then, flatten the new list and pass to the built-in dictionary function:
d = { 1: ['a', 'b'], 2: ['c'] }
new_d = dict([c for h in [[(i, a) for i in b] for a, b in d.items()] for c in h])
Output:
{'a': 1, 'c': 2, 'b': 1}
How could dictionaries whose values are lists be merged in Python, so that all of the keys are moved into one dictionary, and all the elements of each list moved into a single list for each key?
For example, with these dictionaries:
x = {'a': [2], 'b': [2]}
y = {'b': [11], 'c': [11]}
... the result of the merging should be like this:
{'a': [2], 'b': [2, 11], 'c': [11]}
How could this be done with any number of dictionaries, not just two?
for k, v in y.items():
x.setdefault(k, []).extend(v)
You can use following approach, which uses sets and dict comprehension
x = {'a': [2], 'b': [2]}
y = {'b': [11], 'c': [11]}
all_keys = set(x) | set(y)
print {k:x.get(k, [])+y.get(k, []) for k in all_keys}
Results:
{'a': [2], 'c': [11], 'b': [2, 11]}
To collect all the lists together, form a result dictionary that maps your keys to lists. The simplest way to do this is with dict.setdefault() followed by a call to list.extend to grow the lists:
r = {}
for d in [x, y]:
for k, v in d.items():
r.setdefault(k, []).extend(v)
A little more elegant way is with collections.defaultdict() where the automatic default is a new empty list:
from collections import defaultdict
r = defaultdict(list)
for d in [x, y]:
for k, v in d.items():
r[k].extend(v)
Here's a solution that works for an arbitrary number of dictionaries:
def collect(*dicts):
result = {}
for key in set.union(*(set(d) for d in dicts)):
result[key] = sum((d.get(key, []) for d in dicts), [])
return result
It's essentially a generalisation of Tanveer's answer, taking advantage of the fact that set.union() can accept any number of dictionaries as arguments.
Here's an example of the function in use:
>>> x = {'a': [2], 'b': [2]}
>>> y = {'b': [11], 'c': [11]}
>>> collect(x, y)
{'a': [2], 'c': [11], 'b': [2, 11]}
... and with multiple dictionaries:
>>> z = {'c': [12, 13], 'd': [5]}
>>> collect(x, y, z)
{'a': [2], 'c': [11, 12, 13], 'b': [2, 11], 'd': [5]}
x = {'a': [2], 'b': [2]}
y = {'b': [11], 'c': [11]}
result = {}
for key,value in x.iteritems():
result[key] = value
for key,value in y.iteritems():
if key in result:
for l in value:
result[key].append(l)
else:
result[key] = value
print result
I have a list of lists of data:
[[1422029700000, 230.84, 230.42, 230.31, 230.32, 378], [1422029800000, 231.84, 231.42, 231.31, 231.32, 379], ...]
and a list of keys:
['a', 'b', 'c', 'd', 'e']
I want to combine them to a dictionary of lists so it looks like:
['a': [1422029700000, 1422029800000], 'b': [230.84, 231.84], ...]
I can do this using loops but I am looking for a pythonic way.
It is quite simple:
In [1]: keys = ['a','b','c']
In [2]: values = [[1,2,3],[4,5,6],[7,8,9]]
In [7]: dict(zip(keys, zip(*values)))
Out[7]: {'a': (1, 4, 7), 'b': (2, 5, 8), 'c': (3, 6, 9)}
If you need lists as values:
In [8]: dict(zip(keys, [list(t) for t in zip(*values)]))
Out[8]: {'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]}
or:
In [9]: dict(zip(keys, map(list, zip(*values))))
Out[9]: {'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]}
Use:
{k: [d[i] for d in data] for i, k in enumerate(keys)}
Example:
>>> data=[[1422029700000, 230.84, 230.42, 230.31, 230.32, 378], [1422029800000, 231.84, 231.42, 231.31, 231.32, 379]]
>>> keys = ["a", "b", "c"]
>>> {k: [d[i] for d in data] for i, k in enumerate(keys)}
{'c': [230.42, 231.42], 'a': [1422029700000, 1422029800000], 'b': [230.84, 231.84]}
Your question has everything in a list so if you want a list of dicts:
l1= [[1422029700000, 230.84, 230.42, 230.31, 230.32, 378], [1422029800000, 231.84, 231.42, 231.31, 231.32, 379]]
l2 = ['a', 'b', 'c', 'd', 'e',"f"] # added f to match length of sublists
print([{a:list(b)} for a,b in zip(l2,zip(*l1))])
[{'a': [1422029700000, 1422029800000]}, {'b': [230.84, 231.84]}, {'c': [230.42, 231.42]}, {'d': [230.31, 231.31]}, {'e': [230.32, 231.32]}, {'f': [378, 379]}]
If you actually want a dict use a dict comprehension with zip:
print({a:list(b) for a,b in zip(l2,zip(*l1))})
{'f': [378, 379], 'e': [230.32, 231.32], 'a': [1422029700000, 1422029800000], 'b': [230.84, 231.84], 'c': [230.42, 231.42], 'd': [230.31, 231.31]}
You example also has a list of keys shorter than the length of your sublists so zipping will actually mean you lose values from your sublists so you may want to address that.
If you are using python2 you can use itertools.izip:
from itertools import izip
print({a:list(b) for a,b in izip(l2,zip(*l1))
I have found many threads for sorting by values like here but it doesn't seem to be working for me...
I have a dictionary of lists that have tuples. Each list has a different amount of tuples. I want to sort the dictionary by how many tuples each list contain.
>>>to_format
>>>{"one":[(1,3),(1,4)],"two":[(1,2),(1,2),(1,3)],"three":[(1,1)]}
>>>for key in some_sort(to_format):
print key,
>>>two one three
Is this possible?
>>> d = {"one": [(1,3),(1,4)], "two": [(1,2),(1,2),(1,3)], "three": [(1,1)]}
>>> for k in sorted(d, key=lambda k: len(d[k]), reverse=True):
print k,
two one three
Here is a universal solution that works on Python 2 & Python 3:
>>> print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
two one three
dict= {'a': [9,2,3,4,5], 'b': [1,2,3,4, 5, 6], 'c': [], 'd': [1,2,3,4], 'e': [1,2]}
dict_temp = {'a': 'hello', 'b': 'bye', 'c': '', 'd': 'aa', 'e': 'zz'}
def sort_by_values_len(dict):
dict_len= {key: len(value) for key, value in dict.items()}
import operator
sorted_key_list = sorted(dict_len.items(), key=operator.itemgetter(1), reverse=True)
sorted_dict = [{item[0]: dict[item [0]]} for item in sorted_key_list]
return sorted_dict
print (sort_by_values_len(dict))
output:
[{'b': [1, 2, 3, 4, 5, 6]}, {'a': [9, 2, 3, 4, 5]}, {'d': [1, 2, 3, 4]}, {'e': [1, 2]}, {'c': []}]