A dictionary list?

S

Steve

Hi,

How can I create a list of a dictionary? (in other words, I need to
create an array of a dictionary). Please help!

Steve
 
F

Francis Avila

Steve wrote in message said:
Hi,

How can I create a list of a dictionary? (in other words, I need to
create an array of a dictionary). Please help!

Steve

I am unsure how to interpret "of a". Do you mean a list *from* a
dictionary" or a list *of* dictionaries? "Array of a dictionary" suggests
you mean "array of dictionaries".

dictarray = [{} for i in range(10)]

listfromdict = {}.items()

Note the subtle trap of using 'dictarray = [{}]*10' instead: this will
create only one dictionary, with ten references to it.


In any case, this is an *extremely* basic question. Have you gone through
the included tutorial yet?
 
G

Gary Herron

Hi,

How can I create a list of a dictionary? (in other words, I need to
create an array of a dictionary). Please help!

Steve

That question is not very specific but perhaps dictionary methods
"key", "values", or "items" might be what you want:
# Here is a sample dictionary
d = {1:'one', 2:'two', 3:'three'}

# Get a list of its keys
d.keys() [1, 2, 3]

# Get a list of its values
d.values() ['one', 'two', 'three']

# Get a list of (key,value) tuples
d.items()
[(1, 'one'), (2, 'two'), (3, 'three')]


Hope that helps,

Gary Herron
 
E

Eli Pollak

Do you mean you want an iterable dictionary ?
Such as in php :

$arr = array()
$arr[0] = 'a';
$arr[1] = 'b';
$arr['somestr'] = 'str';
$arr[2] = 'c';

foreach($arr as $element)
print $element

which prints

'a','b','str','c'

Or do you mean something else ?

Cheers,
Eli
 
L

Lee Harr

Do you mean you want an iterable dictionary ?
Such as in php :

$arr = array()
$arr[0] = 'a';
$arr[1] = 'b';
$arr['somestr'] = 'str';
$arr[2] = 'c';

foreach($arr as $element)
print $element

which prints

'a','b','str','c'


Or, as in python, even ...
arr = {}
arr[0] = 'zero'
arr[1] = 'one'
arr['something'] = 'other'
arr[3] = 'three'
for x in arr:
.... print x, arr[x]
....
0 zero
1 one
3 three
something other
['zero', 'one', 'three', 'other']
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,937
Members
47,481
Latest member
ElviraDoug

Latest Threads

Top