Initialise dictionary of dictionary

A

Ayushi Dalmia

I need to initialise a dictionary of dictionary with float values. I do not know the size of the dictionary beforehand. How can we do that in Python
 
T

Tim Chase

I need to initialise a dictionary of dictionary with float values.
I do not know the size of the dictionary beforehand. How can we do
that in Python --

Either

d = {}

or, if you want

from collections import defaultdict
d = defaultdict(float)
print(d["Hello"])

If you really do want a dict-of-dict that defaults to floats, you can
do

d = defaultdict(lambda: defaultdict(float))
print(d[3141]["Hello"])

-tkc
 
D

Dave Angel

Ayushi Dalmia said:
I need to initialise a dictionary of dictionary with float values. I do not know the size of the dictionary beforehand. How can we do that in Python

Do what? There's no concept of pre-initializing a dictionary, and
there's no specific limit to its eventual size.

Unsure of what the floats have to do with it. Perhaps you meant
float KEYS.
 
T

Tim Chase

Unsure of what the floats have to do with it. Perhaps you meant
float KEYS.

using floats for keys can be dangerous, as small rounding errors in
math can produce keys different enough that they're not found by an
exact-match lookup. But yeah, the original problem specification was
rather wanting in detail. I tried my best at interpreting it, for
whatever that may be worth.

-tkc
 
A

Ayushi Dalmia

Thank you so much Tim. This is precisely what I wanted to do!

I need to initialise a dictionary of dictionary with float values.
I do not know the size of the dictionary beforehand. How can we do
that in Python --



Either



d = {}



or, if you want



from collections import defaultdict

d = defaultdict(float)

print(d["Hello"])



If you really do want a dict-of-dict that defaults to floats, you can

do



d = defaultdict(lambda: defaultdict(float))

print(d[3141]["Hello"])



-tkc
 

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
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top