Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add values in keys in a dictionary inside a loop?

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..

like image 967
Mpizos Dimitris Avatar asked Dec 04 '14 21:12

Mpizos Dimitris


People also ask

How do you access dictionary values in a for loop?

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.

How do I add an item to a dictionary key in Python?

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.

How do you add a value to an existing 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.


1 Answers

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.

like image 118
PeterE Avatar answered Oct 13 '22 00:10

PeterE