Adding 1 to Value in Dictionary - python

I have seen others ways of adding 1 to a value in a dictionary.
I simply keep getting an error when I try to add a value of 1 to a dictionary key value in python.
Here is my code:
arr = {('1', '20'): [0], ('15', '14'): [0]}
I want to add 1 to key ('1', '20').
Here is my code:
w = 1
x = 20
arr[(w, x)] += 1
I get the error code:
TypeError: 'int' object is not iterable
I simply do not know what I am doing wrong. Any suggestions are greatly appreciated.

Two issues:
The keys of your dictionary are tuples of strings, but you're trying to index into the dictionary using a tuple of ints.
The values in your dictionary are (1-length) lists of ints, but you're trying to add a number to one of those lists.
You might want something like this:
w = '1'
x = '20'
arr[(w, x)][0] += 1
Without seeing more of your code, it could be that you want something more like this:
# dictionary mapping tuples of ints to ints
arr = { (1, 20): 0, (15, 14): 0 }
# now we can just use ints
w = 1
x = 20
# and no need to use [0] to get the first element of the list
# (because it's no longer a list)
arr[(w, x)] += 1

Related

How to get dictionary keys using a tuple, where dictionary keys are stored in list and values in tuple

dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
"""code here"""
For the above code I need to get the output as :
a
b
c
I know if we put print(i), we will get the desired output, but the answer expected is in terms of K.
Actual answer is: print(k[0]),which I am unable to understand.
Thanks
Since you define values of dictionary equal to a tuple here:
dictionary[my_list[i]] = (my_list[i],)
k is a tuple which means for it to print the actual value you need to get the first item in k by using the following:
dictionary = {}
my_list = ['a','b','c','d']
for i in range(len(my_list)-1):
dictionary[my_list[i]] = (my_list[i],)
for i in sorted (dictionary.keys()):
k = dictionary[i]
print(k[0])
Output:
a
b
c
k[0] just gets the first item in the tuple ('a',). This makes it print a instead of ('a',).

the difference between list and dictionary in python

code A :
t1 = {}
t1[0] = -5
t1[1] = 10.5
code B :
t2 = []
t2[0] = -5
t2[1] = 10.5
why code B has "IndexError: list assignment index out of range" and how to solve it?
Dictionaries are hashsets. They pair arbitrary (hashable) keys with values, and there is no expectation that those keys are consecutive, or even in fact numbers
replacement_dict = {'old_name': 'new_name'} # you could use this to implement a find/replace
By comparison, lists are densely-packed and their indices (not keys -- this is a different term accessed the same way with the object[index] notation) are numbers. Because of this, you can't just access a random value that's greater than the length of the list, you must use append instead.
lst = []
lst[0] = 'blah' # throws an IndexError because len(lst) is 0
lst.append('blah')
assert lst[0] == 'blah
Dictionaries work like key-value pairs. Every time you assign a new value in a dictionary, you create a new key-value pair.
A list is like an array that you can extend at will, but if you try to access an index that is over its current size, it will return an error. You typically extend a list by using t2.append(value).
A dictionary allows assignment of elements that don't exist yet. Lists don't. That's just the way they're designed.
You can fix this two ways. First is to initialize the list to the size it needs to be:
t2 = [None]*2
The second is to call append instead of using =:
t2 = []
t2.append(-5)
t2.append(10.5)
A dictionary stores data with name values.
dictionary = {"name": "value"}
print(dictionary["name"])
# Prints "value".
A list stores a sequence of values. There aren't any names for the values, they are accessed via an index.
list = ["value", "other value"]
print(list[0])
# Prints "value".
To fix your problem use append.
t2 = []
t2.append(-5)
t2.append(10.5)

"group" items in list

I have
[string, int,int],[string, int,int]... kind of list that I want to group with a different list
[string1, int1,int1] + [string2, int2,int2] = ["string+string2", int1+int1+int2+int2]
the History goes like I have already made import function that gets me compounds:
ex[Ch3, 15.3107,15.284] kinda like this...
I have a function that gives me:
dictionary{0:"CH3"}
and another that gives me:
List ["CH3",30.594700000000003]
def group_selectec_compounds(numCompound,values)
values can be list of list that have everything
I also have dic made that is something like this {0:["CH4"],...}
numCoumpound should be various variables (I think) or tuple of keys? So I can do the math for the user.
In the end I want something like: ["CH3+CH4",61.573]
it can also be: ["CH3+CH4+H2SO4",138.773]
I would solve this using '+'.join, sum and comprehensions:
>>> data = [['string1', 2, 3], ['string2', 4, 5], ['string3', 6, 7]]
>>> ['+'.join(s for s, _, _ in data), sum(x + y for _, x, y in data)]
['string1+string2+string3', 27]
First, create a dictionary that stores the location of the type:
helper = {}
for elem in lst1:
elemType = str(type(elem))
if elemType not in helper:
helper[elemType] = lst1.index[elem]
Now you have a dictionary that indexes your original list by type, you just have to run the second list and append accordingly:
for elem in lst2:
elemType = str(type(elem))
if elemType not in helper:
#in case list 2 contains a type that list 1 doesn't have
lst1.append(elem)
helper[elemType] = lst1.index[elem]
else:
lst1[helper[elemType]] += elem
Hope this makes sense! I have not vetted this for correctness but the idea is there.
Edit: This also does not solve the issue of list 1 having more than 1 string or more than 1 int, etc., but to solve that should be trivial depending on how you wish to resolve that issue.
2nd Edit: This answer is generic, so it doesn't matter how you order the strings and ints in the list, in fact, lst1 can be [string, int, double] and lst2 can be [int, double, string] and this would still work, so it is robust in case the order of your list changes

converting list into dictionary with index as key [duplicate]

This question already has answers here:
One liner: creating a dictionary from list with indices as keys
(5 answers)
Why do I get "List index out of range" when trying to add consecutive numbers in a list using "for i in list"? [duplicate]
(4 answers)
Closed 4 years ago.
To convert a list into a dictionary with key as the index of the element and values as the value in the list. i have tried to create it but was facing errors.below is my current code
for each in list:
dict[each] = list[each]
what is wrong in my code. i am a beginner in python.
Try using enumerate! It's nifty:
list = ['a','b','c']
print(dict(enumerate(list))) # >>> {0: 'a', 1: 'b', 2: 'c'}
what is wrong with your code is that you are taking two elements of a list (by subscripting them with the list[value] syntax) and setting them equal to each other.
What you meant to do:
d = {}
l = ['a','b','c']
for k,v in enumerate(l):
d[k] = v
What this does:
Enumerating a sequence gives you a tuple where an integer is paired with the value of the sequence.Like in my list above, the enumerate(list) itself would be:
for k in enumerate([1,2,3]):
print(k)
Result: (0, 1)
(1, 2)
(2, 3)
The k and v in the loop first for loop I wrote unpacks the tuples (k= the index 0 of the tuple, v = the second), and the predefined dict (d in my case) sets the enumerate value (d[k], the key) to the value k (the second value of the tuple after enumeration)
Hope this makes sense!
dict = {}
for each in list:
dict[each] = list[each]
Take for array list = [1,2,34,22] an example
dict[1] = list[1] # list[1] = 2
dict[2] = list[2] # list[2] = 34
dict[34] = list[34] # Error size is just 4 , accessing list[34] will give index error
Try this simple code
a = [1,2,34,22]
dict = {}
for i in range(len(a)):
dict[i]=a[i]
print(dict)
the following code will work
lst = [1,2,3,4]
result = {i:j for i,j in enumerate(lst)}

Replace first elements of tuple with zero over a certain length

I have a sorted list based on first element:
A = [(0.11, '201405'), (0.41, '201402'),.....,(1.5, '201430')] # values and time
and want to change first element of each tuple:
x = len(C) # C is a list and its length is 2
y = len(D) # D is a list and its length is 1
if x > y:
A[0[0:x]] = 0.0 # if x > y then set first element of A equal to zero (over length of C)
But I get following error:
TypeError: 'int' object is not subscriptable
Please suggest to fix it.
If I understand your question correctly, you want to replace the first element in each of the first few tuples with 0. Tuples are not modifyable, so you can not modify the existing tuples in the list, but you have to create a new list, holding new tuples. You can do this using a list comprehension.
Example:
>>> A = [(1,"a"), (2,"b"), (3,"c"), (4,"d")]
>>> A = [(x if i > 1 else 0, y) for i, (x, y) in enumerate(A)]
>>> print A
[(0, 'a'), (0, 'b'), (3, 'c'), (4, 'd')]
This will enumerate all the entries in the list, and for each entry create a tuple with the first element being 0, if the index i of that entry is lower than some threshold, or the original value otherwise.
As iharob mentioned, you have a subscript notation error.
Tuples are immutable. You can't just replace 1 element of the tuple in your list. You have to replace the whole tuple with another tuple containing 0.0 as first value and the existing second value. Note that lists are modifiable but tuples aren't. That's why you can update the list A, but you have to replace the tuple with a new tuple.
Here's an example that does not recreate the whole list:
for i, t in enumerate(A):
if i < 1:
A[i] = (0, t[1])
You have an error in A[0[0:x]] = 0.0 you are using subscript notation for the number 0.
Furthermore, the tuple is an immutable type. Hence, it is impossible to change the content of a tuple. You'd better to generate a new list such as:
A = [0.0]+A[1:]

Categories

Resources