You can't .append() to a string because a string is not mutable. If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list. The easiest way to do this is just to add the single item as a list in the first place.
if clientKey not in data:
data[clientKey] = [ref] # single-item list
Now you can data[clientkey].append() all day long.
A simpler approach for this problem is to use collections.defaultdict. This automatically creates the item when it's not there, making your code much simpler.
from collections import defaultdict
data = defaultdict(list)
# ... same as before up to your if
if clientkey in data and ref in data[clientkey]:
print("That invoice already exists")
else:
data[clientKey].append(ref)
Answer from kindall on Stack OverflowI am currently using a while loop to loop and get certain values. I then want to append these values to a dictionary. Every loop through I want to append to two keys
General structure of the code: https://pastebin.com/p4hJcKR5
I have tried using:
dict[key] = value
dict.append(value)
And neither have worked, dict.append gives an error and dict[key] just sets the dictionary to the most recent iteration instead of iterating for all values. Any help would be appreciated.
You can't .append() to a string because a string is not mutable. If you want your dictionary value to be able to contain multiple items, it should be a container type such as a list. The easiest way to do this is just to add the single item as a list in the first place.
if clientKey not in data:
data[clientKey] = [ref] # single-item list
Now you can data[clientkey].append() all day long.
A simpler approach for this problem is to use collections.defaultdict. This automatically creates the item when it's not there, making your code much simpler.
from collections import defaultdict
data = defaultdict(list)
# ... same as before up to your if
if clientkey in data and ref in data[clientkey]:
print("That invoice already exists")
else:
data[clientKey].append(ref)
You started with a string value, and you cannot call .append() on a string. Start with a list value instead:
if clientKey not in data:
data[clientKey] = [ref]
Now data[clientKey] references a list object with one string in it. List objects do have an append() method.
Your key variable holds only the value of each key of the dict for each iteration, and if you assign a new value to the key, it only updates that key variable, not the dict. You should update the dict itself by referencing the key of the dict in each assignment:
for key in signames:
signames[key] = '_' + signames[key]
But as @jpp pointed out in the comment, it would be more idiomatic to iterate over signames.items() instead, since the expression in the assignment also involves the value of each key:
for key, value in signames.items():
signames[key] = '_' + value
You can do classic dict comprehension here:
signames = {k: '_'+ v for k,v in signames.items()}
Just use append:
list1 = [1, 2, 3, 4, 5]
list2 = [123, 234, 456]
d = {'a': [], 'b': []}
d['a'].append(list1)
d['a'].append(list2)
print d['a']
You should use append to add to the list. But also here are few code tips:
I would use dict.setdefault or defaultdict to avoid having to specify the empty list in the dictionary definition.
If you use prev to to filter out duplicated values you can simplfy the code using groupby from itertools
Your code with the amendments looks as follows:
import itertools
def make_drug_dictionary(data):
drug_dictionary = {}
for key, row in itertools.groupby(data, lambda x: x[11]):
drug_dictionary.setdefault(key,[]).append(row[?])
return drug_dictionary
If you don't know how groupby works just check this example:
>>> list(key for key, val in itertools.groupby('aaabbccddeefaa'))
['a', 'b', 'c', 'd', 'e', 'f', 'a']
The append function you're referencing only works for lists: https://docs.python.org/2/tutorial/datastructures.html
If you want to add a new key/value pair to a dictionary, use: dictionary['key'] = value .
You can also opt for: dictionary.update({'key': value}), which works well for adding multiple key/value pairs at once.
You need to initialize a list rather than just adding the object. Change this:
parents[parent]=kid
to this:
parents[parent] = [kid]
This will give you a list to which you can append() new objects, rather than just a string.
You create a new key/value pair on a dictionary by assigning a value to that key
d = {'key': 'value'}
print(d) # {'key': 'value'}
d['mynewkey'] = 'mynewvalue'
print(d) # {'key': 'value', 'mynewkey': 'mynewvalue'}
If the key doesn't exist, it's added and points to that value. If it exists, the current value it points to is overwritten.
I feel like consolidating info about Python dictionaries:
Creating an empty dictionary
data = {}
# OR
data = dict()
Creating a dictionary with initial values
data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}
Inserting/Updating a single value
data['a'] = 1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
Inserting/Updating multiple values
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Python 3.9+:
The update operator |= now works for dictionaries:
data |= {'c':3,'d':4}
Creating a merged dictionary without modifying originals
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
Python 3.5+:
This uses a new feature called dictionary unpacking.
data = {**data1, **data2, **data3}
Python 3.9+:
The merge operator | now works for dictionaries:
data = data1 | {'c':3,'d':4}
Deleting items in dictionary
del data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
Check if a key is already in dictionary
key in data
Iterate through pairs in a dictionary
for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
Create a dictionary from two lists
data = dict(zip(list_with_keys, list_with_values))
You cannot append to a string. Form a list first so you can append to it later:
oscars[newcategory] = [nominees]
As has been mentioned, if you create a key's value as a string, you can't use append on it, but you can if you make the key's value a list. Here is one way to do so:
newcategory=input("Enter new category: ")
oscars[newcategory]=[]
addnewnominees = 'yes'
while addnewnominees.lower() != "no":
nominees=input("Enter new nominee: ")
oscars[newcategory].append(nominees)
addnewnominees = str(input("Do you want to enter more nominees: (yes/no):"))