I have the following list:
x=['a','3','4','b','1','2','c','4','5']
How can i make the following dictionary:
b = {'a':[3,4],'b':[1,2],'c':[4,5]}
I tried the following:
Category = defaultdict(int)
for i in a:
if Varius.is_number(i)==False:
Category[i]=[]
keys.append(i)
else:
Category[keys(i)] = i
The keys are created but after i have problem to insert the values.(is_number
is a function which check if the value of the list is number or string).First day away of MATLAB.First day in Python..
In Python, to iterate the dictionary ( dict ) with a for loop, use keys() , values() , items() methods. You can also get a list of all keys and values in the dictionary with those methods and list() . Use the following dictionary as an example.
The easiest way to add an item to a Python dictionary is simply to assign a value to a new key. Python dictionaries don't have a method by which to append a new key:value pair. Because of this, direct assignment is the primary way of adding new items to a dictionary.
Summary: We can add / append new key-value pairs to a dictionary using update() function and [] operator. We can also append new values to existing values for a key or replace the values of existing keys using the same subscript operator and update() function.
Here an example that actually uses the feature that defaultdict
provides over the normal dict
:
from collections import defaultdict
x=['a','3','4','b','1','2','c','4','5']
key='<unknown>' # needed if the first value of x is a number
category = defaultdict(list) # defaultdict with list
for i in x:
if i.isalpha():
key = i;
else:
category[key].append(i) # no need to initialize with an empty list
print category
Also: you should use lower case names for class instances. Uppercase names are usually reserved for classes. Read pep8 for a style guide.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With