I was trying to insert key and value of my dictionary to a python list.I cant seem to figure it out how to do this.
my_dict={test1:[1,2,3,4],test2:[2,3,4,5]}
what I want is
my_list = [['test1', 1,2,3,4], ['test2', 2,3,4,5]]
I am new to python so any help would be appreciated.
This should do it
We need to iterate over the dictionary, and make a list with the key and values, note that we need to unroll the value array *value in order to append to the list
my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}
#Iterate over key and value, and make a list from them, unrolling the value since it is a list
my_list = [[key, *value] for key, value in my_dict.items()]
print(my_list)
#[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]
Using a list comprehension
Ex:
my_dict={"test1":[1,2,3,4],"test2":[2,3,4,5]}
my_list = [[k] +v for k, v in my_dict.items()]
print(my_list)
Output:
[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]
The other solutions use list comprehensions which may be too complicated for someone who is new to python, so this is a solution without list comprehension.
my_dict={"test1":[1,2,3,4],"test2":[2,3,4,5]}
new_list = []
for key, value in my_dict.items():
print(key, value)
temp = []
temp.append(str(key))
for a in value:
temp.append(a)
new_list.append(temp)
print(new_list)
# [['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]
Here's a version without the list comprehension, I remember it took me a couple months to understand the syntax when I was new to python.
my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}
my_list = []
for key, value in my_dict.items():
my_list.append([key, *value]) # the '*value' bit means all elements of the 'value' variable
print(my_list)
FOMO:
my_dict={'test1':[1,2,3,4],'test2':[2,3,4,5]}
x = lambda a:[a[0],*a[1]]; print([x(i) for i in my_dict.items()])
#[['test1', 1, 2, 3, 4], ['test2', 2, 3, 4, 5]]
Related
I have two lists, one containing a list of keys, and another containing the values to be assigned to each key, chronologically, by key.
For example;
key_list = ['cat', 'dog', 'salamander']
value_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
I'm looking to make a quick method that takes these two lists, and from it can spit out a dictionary that looks like this:
key_value_pairs = {
'cat': [1, 4, 7],
'dog': [2, 5, 8],
'salamander': [3, 6, 9]
}
Regardless of the length of the values, I'm looking for a way to just iterate through each value and amend them to a dictionary containing one entry for each item in the key_list. Any ideas?
key_value_pairs = {k: [v for v_i, v in enumerate(value_list) if v_i % len(key_list) == k_i] for k_i, k in enumerate(key_list)}
Edit: that's a fun one-liner, but it has worse time complexity than the following solution, which doesn't use any nested loops:
lists = [[] for _ in key_list]
for i, v in enumerate(value_list):
lists[i % len(key_list)].append(v)
key_value_pairs = dict(zip(keys, lists))
Based on the number of time the for loop runs, I get multiple list. I want to merge all those list and make one list.
for example:
list = []
for i in item:
list.append(i)
print(list)
How can I merge all the list I get to one list ?
If your item is list of lists, then you can use extend to achieve the same.
lst = []
for i in item:
lst.append(i)
out = []
for sublist in lst:
out.extend(sublist)
print(out)
Also, avoid using python keywords like list for the variable name, use something like lst instead.
You should avoid using list as a variable name, it's a reserved word for python lists.
This code should work for you:
list_ = []
f_list = []
item = [1,2,3,4,5]
for i in item:
list_.append(i)
f_list.extend(list_)
print(list_)
print("Final list - ", f_list)
Output:
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
Final list - [1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5]
I currently have a bunch of lists defined something like below:
old_list = [1, 2, 3, 4, 5]
I'm currently replacing the first element of that list then placing the contents of the list into a dictionary (where the key is the old element 0 value) by doing the following:
old_value = old_list[0]
old_list[0] = 'new value'
test_dict[old_value] = old_list
I was wondering, is this the best way to accomplish this? I was wondering if there was a way to make this a bit more efficient with list comprehension so it could look something a bit more like this:
test_dict[old_list[0]] = [i for idx, i in enumerate(old_list) if '''relevant conditions to replace element 0''']
A readable form can be achieved with unpacking:
head, *tail = old_list
# if test_dict already exists
test_dict[head] = ["new value"] + tail
# otherwise
test_dict = {head: ["new value"] + tail}
# {1: ['new value', 2, 3, 4, 5]}
Here is one way to do it
Code
old_list = [1, 2, 3, 4, 5]
new_value = 'new'
test_dict = {}
test_dict[old_list[0]] = [new_value] + old_list[1:]
print(test_dict)
Output
{1: ['new', 2, 3, 4, 5]}
Generalised form
old_list = [1, 2, 3, 4, 5]
idx = 2
new_value = 'new'
test_dict = {}
test_dict[old_list[idx]] = old_list[:idx] + [new_value] + old_list[idx+1:]
print(test_dict)
Output
{3: [1, 2, 'new', 4, 5]}
I have a dictionary like this:
a = {(8, 9): [[0, 0], [4, 5]], (3, 4): [[1, 2], [6, 7]]}
I would like to subtract the sum of the corresponding elements of the nested lists in the values from each element of each key, and replace the key with the result.
For example:
new_key[0] = 8 - 0+4 = 4, new_key[1] = 9 - (0+5) = 4
Hence the new key becomes (4, 4) and it replaces (8, 9)
I am not able to understand how to access a list of lists which is the value to the key!
Any ideas as to how to do this?
See Access item in a list of lists for indexing list of list.
For your specific case, this should work
b = {(k[0]-v[0][0]-v[1][0], k[1]-v[0][1]-v[1][1]):v for k, v in a.items()}
for key in list(a.keys()):
new_key = []
new_key.append(key[0] - (a[key][0][0] + a[key][1][0]))
new_key.append(key[1] - (a[key][0][1] + a[key][1][1]))
a[new_key] = a.pop(key) # pop() returns the value
Iterate through the dictionary to get the keys and values and create a new one b. Then just point a to the new dictionary b
a = {(8, 9): [[0, 0], [4, 5]], (3, 4): [[1, 2], [6, 7]]}
b = {}
for key, val in a.items():
new_key = (key[0]-(val[0][0]+val[1][0]), key[1]-(val[0][1]+val[1][1]))
b[new_key] = val
a = b
del b
Try This:
b = {}
for key, value in a.items():
new_key = key[0]-(value[0][0]+value[1][0])
new_key_1 = key[1]-(value[0][1]+value[1][1])
u_key = (new_key, new_key_1)
b[u_key]=value
print(b)
The following code will work just as well with any size of key tuple (2, 5, 87, whatever.)
There is no simple way to rename a dictionary key, but you can insert a new key and delete the old one. This isn't recommended for a couple of reasons:
to be safe, you'll need to check to make sure you're not doing something weird like creating a new key only to delete that same key
be careful when you iterate over a dictionary while changing it
If you need a dictionary result, the safest thing is to generate an entirely new dictionary based on a, as has been done here.
The problem you're trying to solve is easier if you transpose the dictionary values.
After calculating the new key, (8, 9): [[0, 0], [4, 5]] should become:
(8 - sum([0, 4]), 9 - sum([0, 5])): [[0, 0], [4, 5]]
Now see how transposing helps:
transposed([[0, 0], [4, 5]]) == [[0, 4], [0, 5]]
then the new key[0] calculation is:
key[0] - sum(transposed(values)[0])
and the new key[1] calculation is:
key[1] - sum(transposed(values)[1])
So transposing makes the calculation easier.
Python dictionaries can't have lists as keys (lists are not hashable) so I've built the key as a list, then converted it to a tuple at the end.
a = {
(8, 9): [[0, 0], [4, 5]],
(3, 4): [[1, 2], [6, 7]]
}
def transpose(m):
return list(zip(*m))
results = {}
for source_keys, source_values in a.items():
transposed_values = transpose(source_values)
key = []
for n, key_item in enumerate(source_keys):
subtractables = sum(transposed_values[n])
key.append(key_item - subtractables)
results[tuple(key)] = source_values
print(results)
>>> python transpose.py
{(4, 4): [[0, 0], [4, 5]], (-4, -5): [[1, 2], [6, 7]]}
The following solution works with three assumptions:
The keys are iterables of integers
The values are iterables of iterables of integers
The inner iterables of each value are the same length as the corresponding key
Practically, this means that the length of the value can be anything, as long as it's a 2D list, and that you can have keys of different lengths, even in the same dictionary, as long as the values match along the inner dimension.
You would want to transpose the values to make the sum easier to compute. The idiom zip(*value) lets you do this quite easily. Then you map sum onto that and subtract the result from the elements of the key.
Another thing to keep in mind is that replacing keys during iteration is a very bad idea. You're better off creating an entirely new dictionary to hold the updated mapping.
from operator import sub
from itertools import starmap
a = {(8, 9): [[0, 0], [4, 5]], (3, 4): [[1, 2], [6, 7]]}
b = {
tuple(starmap(sub, zip(k, map(sum, zip(*v))))): v
for k, v in a.items()
}
The result is
{(4, 4): [[0, 0], [4, 5]], (-4, -5): [[1, 2], [6, 7]]}
Here is an IDEOne Link to play with.
The full version of the loop would look like this:
b = {}
for k, v in a.items():
vt = zip(*v) # transposed values
sums = map(sum, vt) # sum of the 1st elements, 2nd elements, etc
subs = zip(k, sums) # match elements of key with sums to subtract
diffs = starmap(sub, subs) # subtract sums from key
new_key = tuple(diffs) # evaluate the generators
b[new_key] = value
I want to add multiple values to a specific key in a python dictionary. How can I do that?
a = {}
a["abc"] = 1
a["abc"] = 2
This will replace the value of a["abc"] from 1 to 2.
What I want instead is for a["abc"] to have multiple values (both 1 and 2).
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault is that it initializes the value for that key if that key is not defined. Now, noting that setdefault returns the value, you can combine these into a single line:
a.setdefault("somekey", []).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict methods, in particular the get() method, and do some experiments to get comfortable with this.
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
Append list elements
If the dict values need to be extended by another list, extend() method of lists may be useful.
a = {}
a.setdefault('abc', []).append(1) # {'abc': [1]}
a.setdefault('abc', []).extend([2, 3]) # a is now {'abc': [1, 2, 3]}
This can be especially useful in a loop where values need to be appended or extended depending on datatype.
a = {}
some_key = 'abc'
for v in [1, 2, 3, [2, 4]]:
if isinstance(v, list):
a.setdefault(some_key, []).extend(v)
else:
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 2, 4]}
Append list elements without duplicates
If there's a dictionary such as a = {'abc': [1, 2, 3]} and it needs to be extended by [2, 4] without duplicates, checking for duplicates (via in operator) should do the trick. The magic of get() method is that a default value can be set (in this case empty set ([])) in case a key doesn't exist in a, so that the membership test doesn't error out.
a = {some_key: [1, 2, 3]}
for v in [2, 4]:
if v not in a.get(some_key, []):
a.setdefault(some_key, []).append(v)
a
# {'abc': [1, 2, 3, 4]}