I have a dictionary which consist of lists. Now how will it be possible to add a variable/element in the list for the example provided below.
inventory = {
'gold': 20,
'bag': ['chocolate', 'chips', 'food']
}
Now how do I add something in the list bag.
I have already tried this but it does not work.
inventory.bag.append('test')
inventory.bag.insert('test')
You need to use subscription, so object[...], to address elements in the dictionary:
inventory['bag'].append('test')
Here inventory['bag'] retrieves the value associated with the 'bag' key. This is a list object, so you can then call the append() method on that result.
You need access dict value like inventory['bag'], then because the value is a list, you just need call append method
inventory['bag'].append('test')
Demo of How to Append and Insert element in the list.
List append() method will add given element at the last.
>>> l1 = [11, 12, 13]
>>> l1.append(20)
>>> l1
[11, 12, 13, 20]
# ^
List insert() method will take two arguments, First is index where you want to insert given element and second is element which need to insert.
>>> l1.insert(1, 22)
>>> l1
[11, 22, 12, 13, 20]
# ^
Consider dictionary where key i.e.number have value as List Object.
>>> d = {"number":[11, 12]}
>>> d["number"]
[11, 12]
>>> d["number"].append(22)
>>> d
{'number': [11, 12, 22]}
>>> d["number"].insert(2, 20)
>>> d["number"]
[11, 12, 20, 22]
>>>
Related
I have my array with data referring to different subjects divided in 3 different groups
A = ([12, 13, 15], [13, 16, 18], [15, 15, 17])
I want to append these to 3 different arrays, but I don't want to do it "manually" since I should use this code for bigger set of data.
So, I was looking for a way to create as many arrays as the amount of subjects (in this case 3) assigning to them different "names".
Looking on this site I ended up using a dictionary and this is what I did
number_of_groups = len(A)
groups = {"group" + str(i+1) : [] for i in range(number_of_groups)}
and this is the output:
{'group1': [], 'group2': [], 'group3': []}
now I wasn't able to append to each of them the 3 different set of data. I expect to have:
{'group1': [12, 13, 15], 'group2': [13, 16, 18], 'group3': [15, 15, 17]}
I tried this (I know is not a good way to do it...)
for n in A:
for key in paths: paths[key].append(n)
output:
{'group1': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])],
'group2': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])],
'group3': [array([12, 13, 15]),array([13, 16, 18]),array([15, 15, 17])]}
The issue is that you have a nested loop. The outer one iterates over each group, then the inner one appends each group. To edit your current code, you can try using zip() like this:
for n, key in zip(A, paths):
paths[key].append(n)
However, since you are already using a dictionary comprehension earlier, it is definitely easier to modify that and fill the dictionary at that step already instead of first creating it and then filling it. The following outputs what you need:
groups = {"group" + str(i+1) : group for i, group in enumerate(A)}
>>> {'group1': [12, 13, 15], 'group2': [13, 16, 18], 'group3': [15, 15, 17]}
I'mahdi had already suggested dict-comprehension to build the correct list in first place. In addition, you can use enumerate to iterate all elements a with index i of the tuple A:
groups = {
f"group{i+1}": a
for i, a in enumerate(A)
}
As Rolf of Saxony pointed out, enumerate has an optional start parameter for the iteration index, so you can simplify this further to:
groups = {
f"group{i}": a
for i, a in enumerate(A, 1)
}
I have a list:
list = [10, 15,14,20]
And I would like to sum a variable(lets say add=5) to all elements in that list, to have something like:
newlist = [15,20,19,25]
Thanks for your help.
List comprehension:
l = [10, 15, 14, 20]
nl = [i + 5 for i in l]
Map function:
l = [10, 15, 14, 20]
nl = list(map(lambda i: i+5, l))
print(nl)
[15, 20, 19, 25]
Don't use list keyword
>>> list = [10, 15, 14, 20]
>>> list((3, 5, 7))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-644-e66a8dedf706> in <module>
----> 1 list((3, 5, 7))
TypeError: 'list' object is not callable
You override the function list by a list:
>>> type(list)
type
>>> list = [10, 15, 14, 20]
>>> type(list)
list
Using list comprehension is probably the most pythonic way of doing this.
Like in Corralien's answer (which is very good by the way).
l = [10, 15,14,20]
l = [value+5 for value in l]
This will result in:
l = [15, 20, 19, 25]
In case you don't know how list comprehension works exactly you can break it down into tokens.
The first part value+5 is essentially what is in the for loop and it is what's being appended to the list, and for value in l is just a for loop and goes through each element in list and assigns it to the the variable value
You can use you any type of loop for this.
For example with list comprehension:
list = [10, 15,14,20]
x = 5
new_list = [i+x for i in list]
print(new_list)
First, you shadowed the list function by using it as a variable.
You can use a loop.
list1= [10, 15,14,20]
num1=5
new_l=[num+num1 for num in list1]
print(new_l)
if in case you are looking for pandas solution, as you have pandas tag in your question. below solution will help you.
import pandas as pd
alist = [10, 15,14,20] # initial list
const = 5 # constant you want to add
df= pd.DataFrame(data={"A":alist}) # create a dataframe
df["A"] += const # add constant to dataframe
print(df) # print dataframe
Output:
A
0 15
1 20
2 19
3 25
I have a couple lists (raw data from elsewhere), that I collect in another list, to do stuff with later in the code. (So if I were to edit the raw data I am using, I can just change the original lists, edit the everything-list to reflect added/removed lists, and have all the subsequent code reflect those changes without me having to change anything in the rest of the code.)
Like so:
a=[1,2,3]
b=[55,9,18]
c=[15,234,2]
everything=[a,b,c]
At one point I would like to use the NAMES of my original lists ('a','b', and 'c' in my example).
Is there a way for me to use my list 'everything' to access the names of the lists put in it?
(So for the code
for i in range(len(everything)):
print('The data from',???,'is',everything[i])
??? would be replaced by something to ideally print
The data from a is [1, 2, 3]
The data from b is [55, 9, 18]
The data from c is [15, 234, 2]
)
You can use dictionaries for this.
a=[1,2,3]
b=[55,9,18]
c=[15,234,2]
everything={'a':a,'b': b,'c': c}
for i in range(len(everything['a'])):
everything['a'][i] += 10
print(everything)
# >> {'a': [11, 12, 13], 'b': [55, 9, 18], 'c': [15, 234, 2]}
print(a)
# >> [11, 12, 13]
for var, val in everything.items():
print(f'The data from {var} is {val}')
"""
>>The data from a is [11, 12, 13]
The data from b is [55, 9, 18]
The data from c is [15, 234, 2]
"""
There's a way you can do this, but using a dictionary is equivalent to your case as its keys are unique and can be used as your variable name. Hence, with dictionaries you can retrieve values and print them in any format you need:
a = [1,2,3]
b = [55,9,18]
c = [15,234,2]
everything= {'a': a, 'b': b, 'c': c}
for k, v in everything.items():
print(f'The data from {k} is {v}')
If you are trying to access the variable name using id, this can be used.
a=[1,2,3]
b=[55,9,18]
c=[15,234,2]
everything = [a,b,c]
def get_name(your_id):
name = [x for x,_ in globals().items() if id(_)==your_id ]
return(name[0])
for i in range(len(everything)):
print('The data from',get_name(id(everything[i])),'is',everything[i])
This outputs:
('The data from', 'a', 'is', [1, 2, 3])
('The data from', 'b', 'is', [55, 9, 18])
('The data from', 'c', 'is', [15, 234, 2])
globals is a built-in which returns a dict of variables/values in the global name space. So you could get the variable name given the id.
I have an assignment to add a value to a sorted list using list comprehension. I'm not allowed to import modules, only list comprehension, preferably a one liner. I'm not allowed to create functions and use them aswell.
I'm completely in the dark with this problem. Hopefully someone can help :)
Edit: I don't need to mutate the current list. In fact, I'm trying my solution right now with .pop, I need to create a new list with the element properly added, but I still can't figure out much.
try:
sorted_a.insert(next(i for i,lhs,rhs in enumerate(zip(sorted_a,sorted_a[1:])) if lhs <= value <= rhs),value)
except StopIteration:
sorted_a.append(value)
I guess ....
with your new problem statement
[x for x in sorted_a if x <= value] + [value,] + [y for y in sorted_a if y >= value]
you could certainly improve the big-O complexity
For bisecting the list, you may use bisect.bisect (for other readers referencing the answer in future) as:
>>> from bisect import bisect
>>> my_list = [2, 4, 6, 9, 10, 15, 18, 20]
>>> num = 12
>>> index = bisect(my_list, num)
>>> my_list[:index]+[num] + my_list[index:]
[2, 4, 6, 9, 10, 12, 15, 18, 20]
But since you can not import libraries, you may use sum and zip with list comprehension expression as:
>>> my_list = [2, 4, 6, 9, 10, 15, 18, 20]
>>> num = 12
>>> sum([[i, num] if i<num<j else [i] for i, j in zip(my_list,my_list[1:])], [])
[2, 4, 6, 9, 10, 12, 15, 18]
I am trying to create a list of values that correlate to a string by comparing each character of my string to that of my "alpha_list". This is for encoding procedure so that the numerical values can be added later.
I keep getting multiple errors from numerous different ways i have tried to make this happen.
import string
alpha_list = " ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ints = "HELLO WORLD"
myotherlist = []
for idx, val in enumerate(ints):
myotherlist[idx] = alpha_list.index(val)
print(myotherlist)
Right now this is my current error reading
Traceback (most recent call last):
File "C:/Users/Derek/Desktop/Python/test2.py", line 11, in <module>
myotherlist[idx] = alpha_list.index(val)
IndexError: list assignment index out of range
I am pretty new to python so if I am making a ridiculously obvious mistake please feel free to criticize.
The print(myotherlist) output that i am looking for should look something like this:
[8, 5, 12, 12, 15, 0, 23, 15, 18, 12, 4]
Just use append:
for val in ints:
myotherlist.append(alpha_list.index(val))
print(myotherlist)
myotherlist is an empty list so you cannot access using myotherlist[idx] as there is no element 0 etc..
Or just use a list comprehension:
my_other_list = [alpha_list.index(val) for val in ints]
Or a functional approach using map:
map(alpha_list.index,ints))
Both output:
In [7]: [alpha_list.index(val) for val in ints]
Out[7]: [8, 5, 12, 12, 15, 0, 23, 15, 18, 12, 4]
In [8]: map(alpha_list.index,ints)
Out[8]: [8, 5, 12, 12, 15, 0, 23, 15, 18, 12, 4]
import string - don't use that a bunch of books say its better to use the built in str
myotherlist[idx] = alpha_list.index(val) is why you are getting the error. This is saying 'Go to idx index and put alpha_list.index(val) there, but since the list is empty it cannot do that.
So if you replace
for idx, val in enumerate(ints):
myotherlist[idx] = alpha_list.index(val)
with
for letter in ints: #iterates over the 'HELLO WORLD' string
index_to_append = alpha_list.index(letter)
myotherlist.append(index_to_append)
you will get the expected result!
If there is something not clear please let me know!