Can I append to a list in a dictionary?
test = {'food' : 'apple'}
Is there a command to add 'banana' and turn it into
test = { 'food': ['apple','banana'] }
Thank you
No, since it isn't a list in the first place.
test['food'] = [test['food'], 'banana']
You need to create a dict where the values are lists:
test = {'food' : ['apple']}
test['food'].append('banana')
The simplest solution would just be to just make the value of your hash a list, that may contain just one element. Then for example, you might have something like this:
test = {'food' : ['apple']}
test['food'].append('banana')
I'd recommend using a defaultdict in this case, it's pretty straightforward to deal with dictionaries of lists, since then you don't need two separate cases every time you modify an entry:
import collections
test = collections.defaultdict(list)
test['food'].append('apple')
test['food'].append('banana')
print test
# defaultdict(<type 'list'>, {'food': ['apple', 'banana']})
Related
I saw similar questions but unfortunately I didnt found answer for my problem.
I have a list:
list = ['a_abc', 'a_xyz', 'a_foo', 'b_abc', 'b_xyz', 'b_foo']
I want to split this list into 3 based on character after underscore _.
Desired output would be:
list_1 = ['a_abc', 'b_abc']
list_2 = ['a_xyz', 'b_xyz']
list_3 = ['a_foo', 'b_foo']
I would like to avoid something like:
for element in list:
if 'abc' in element...
if 'xyz' in element...
because I have over 200 strings to group in this way in my use case. So code "should recognize" the same part of the string (after underscore) and group this in sublists.
Since I didnt notice similar issue any advice is highly appreciated.
You shouldn't want to do this with one or more lists, because you don't know at runtime how many there are (or, even if you know, it will be repeated code).
Instead, you can use defaultdict; it's like a default dictionary, but handles missing value simply creating a new element with your specified factory.
In this case, defaultdict(list) means to create a dictionary with a list factory; when a key is missing, the object will create an empty list for that key.
from collections import defaultdict
l = ['a_abc', 'a_xyz', 'a_foo', 'b_abc', 'b_xyz', 'b_foo']
d = defaultdict(list)
for el in l:
key = el.split("_")[1]
# key = el[2:] # use this if the format of elements is <letter>_<other_chars>
d[key].append(el)
print(d)
# defaultdict(<class 'list'>, {'abc': ['a_abc', 'b_abc'], 'xyz': ['a_xyz', 'b_xyz'], 'foo': ['a_foo', 'b_foo']})
print(d["abc"])
# ['a_abc', 'b_abc']
my_text1 = 'text1'
my_text2 = 'text2'
my_list = []
my_dict = {}
my_dict['Key1'] = my_text1
my_dict['Key2'] = my_text2
my_list.append(my_dict)
What's the fastest way to create a list of dictionaries?
Is it possible to use write variable in dictionary?
I wanted to make something like this:
my_list.append('key1'= %s, 'key2'= %s % (my_text1, my_text2))
I know it's wrong syntax but It's my goal to append different values from variables
Use the dictionary literal syntax, {...}
my_list.append({"key1": my_text1, "key2": my_text2})
I'll take it a step further and assume you have a list of texts you want to format as dicts and append to a list:
[{"key%d" % (i + 1) : text for i, text in enumerate(text_list)} for text_list in list_of_lists]
There is this other syntax you can try:
my_list.append(dict(key1=my_text1, key2=my_text2))
Not sure about this issue of "fastest" considering the fact that doing something like this is quite simple in python. The above syntax is probably fastest to write, but I have a feeling that's not what you are after.
The fastest way is to be declarative:
my_list = [{'Key1': 'text1', 'Key2': 'text2'}]
Is it possible to clear all the entries within a dictionary but keep all the keys?
For example if I had:
my_dic={
"colour":[],
"number":[]
}
I put some stuff in them:
my_dic["colour"]='Red'
my_dic["number"]='2'
I can clear these by:
my_dic["colour"] = []
my_dic["number"] = []
But this is long winded if I want to clear a large dictionary quickly, is there a quicker way perhaps using for? I want to keep the keys ["colour"], ["number"], without having to recreate them, just clear all the entries within them.
You can simply clear all lists in a loop:
for value in my_dic.values():
del value[:]
Note the value[:] slice deletion; we are removing all indices in the list, not the value reference itself.
Note that if you are using Python 2 you probably want to use my_dic.itervalues() instead of my_dic.values() to avoid creating a new list object for the loop.
Demo:
>>> my_dic = {'colour': ['foo', 'bar'], 'number': [42, 81]}
>>> for value in my_dic.values():
... del value[:]
...
>>> my_dic
{'colour': [], 'number': []}
You could also replace all values with new empty lists:
my_dic.update((key, []) for key in my_dic)
or replace the whole dictionary entirely:
my_dic = {key: [] for key in my_dic}
Take into account these two approaches will not update other references to either the lists (first approach) or the whole dictionary (second approach).
You no need to delete keys from dictionary:
for key in my_dict:
my_dict[key] = []
One liner:
my_dict = dict.fromkeys(my_dict, None)
You can also replace the None type with other values that are immutable. A mutable type such as a list will cause all of the values in your new dictionary to be the same list.
For mutable types you would have to populate the dictionary with distinct instances of that type as others have shown.
How do I print out my dictionary in the original order I had set up?
If I have a dictionary like this:
smallestCars = {'Civic96': 12.5, 'Camry98':13.2, 'Sentra98': 13.8}
and I do this:
for cars in smallestCars:
print cars
it outputs:
Sentra98
Civic96
Camry98
but what I want is this:
Civic96
Camry98
Sentra98
Is there a way to print the original dictionary in order without converting it to a list?
A regular dictionary doesn't have order. You need to use the OrderedDict of the collections module, which can take a list of lists or a list of tuples, just like this:
import collections
key_value_pairs = [('Civic86', 12.5),
('Camry98', 13.2),
('Sentra98', 13.8)]
smallestCars = collections.OrderedDict(key_value_pairs)
for car in smallestCars:
print(car)
And the output is:
Civic96
Camry98
Sentra98
Dictionaries are not required to keep order. Use OrderedDict.
>>> for car in sorted(smallestCars.items(),key=lambda x:x[1]):
... print car[0]
...
Civic96
Camry98
Sentra98
When you create the dictionary, python doesn't care about in what order you wrote the elements and it won't remember the order after the object is created. You cannot expect it(regular dictionary) to print in the same order. Changing the structure of your code is the best option you have here and the OrderedDict is a good option as others stated.
You can use a tuple (nested) array to do this:
smallestCars = [['Civic86', 12.5],
['Camry98', 13.2],
['Sentra98', 13.8]]
for car, size in smallestCars:
print(car, size)
# ('Civic86', 12.5)
# ('Camry98', 13.2)
# ('Sentra98', 13.8)
I've been fighting with this for quite a long time and need some help, i have some loops searching something and dynamically create dictionary object for them, for example i am scanning a store then all the buckets and then the fruits inside those buckets.
from collections import defaultdict
def tree(): return defaultdict(tree)
test = tree()
test[Store][bucket][fruits] = defaultdict(list)
test[Store][bucket][fruits].append(1)
print test
"""
desired output
{
'Store':{
'bucket1':{
'fruits':['banana', 'mango', 'apple']
}
},
'bucket2':{
'fruits':['banana', 'mango', 'apple']
}
}
}
"""
this approach throws an error and doesn't work, i also tried many other approaches like creating different dictionaries and then merging them, or creating list and then search or find and blah blah.. but i would like to find out how can i merge defaultdict objects inside each other.
can someone please help me with this.
Thanks.
Given your desired output, I don't think you need to use defaultdict(list) at all.
Rather, you can use an ordinary list:
from collections import defaultdict
def tree():
return defaultdict(tree)
test = tree()
test['Store']['bucket']['fruits'] = []
test['Store']['bucket']['fruits'].append(1)
test['Store']['bucket-13']['fruits'] = ['mango', 'apple', 'banana']
print test
However, if you do want to use defaultdict(list), the reason why it's throwing an error is because it is one level too low in your heirarchy. You want to assign it at the "bucket" level, rather then the "fruits" level:
test = tree()
test['Store']['bucket'] = defaultdict(list)
test['Store']['bucket']['fruit'].append('mango')
test['Store']['bucket']['meat'].append('chicken')
# 'fruit' and 'meat' now default to an empty list