473,406 Members | 2,273 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

Pythonic way for missing dict keys

Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem
to find it on the archives (Google seems to have a couple of problems
lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't
learnt yet by heart)

if not my_dict.has_key(key):
my_obj = myobject()
my_dict[key] = my_obj
else:
my_obj = my_dict[key]

2/ try and react on error (this has also a specific name, but...)

try:
my_obj = my_dict[key]
except AttributeError:
my_obj = myobject()
my_dict[key] = my_obj

3/ dict.get usage:

my_obj = my_dict.get(key, myobject())

I am wondering which one is the most recommended way? get usage seems
the clearest, but the only problem I see is that I think myobject() is
evaluated at call time, and so if the initialization is expensive you
will probably see surprises.

thanks in advance,
../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #1
25 4652
On 2007-07-20, Alex Popescu <th***********************@gmail.comwrote:
Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:
There's also the popular collections.defaultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

--
Neil Cerutti
Jul 20 '07 #2
Neil Cerutti <ho*****@yahoo.comwrote in
news:sl*******************@FIAD06.norwich.edu:
On 2007-07-20, Alex Popescu <th***********************@gmail.comwrote:
>Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

There's also the popular collections.defaultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.
This looks like the closest to my needs, but in my case the default value
involves the creation of a custom object instance that is taking parameters
from the current execution context, so I am not very sure I can use it.

../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #3
Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict

Jul 20 '07 #4
Jakub Stolarski <ja*************@gmail.comwrote in
news:11**********************@k79g2000hse.googlegr oups.com:
Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict
I may be missing something but I think the 3 approaches are completely
equivalent in terms of functionality.

../alex
--
..w( the_mindstorm )p.

Jul 20 '07 #5
On Fri, 2007-07-20 at 19:39 +0000, Alex Popescu wrote:
Neil Cerutti <ho*****@yahoo.comwrote in
news:sl*******************@FIAD06.norwich.edu:
On 2007-07-20, Alex Popescu <th***********************@gmail.comwrote:
Hi all!

I am pretty sure this has been asked a couple of times, but I
don't seem to find it on the archives (Google seems to have a
couple of problems lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:
There's also the popular collections.defaultdict.

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

This looks like the closest to my needs, but in my case the default value
involves the creation of a custom object instance that is taking parameters
from the current execution context, so I am not very sure I can use it.
If by "current execution context" you mean globally visible names, this
should still be possible:
>>from collections import defaultdict
def make_default():
.... return x+y
....
>>dd = defaultdict(make_default)
x = 40
y = 2
print dd[0]
42
>>x = "Dead"
y = " Parrot"
print dd[1]
Dead Parrot
>>print dd
defaultdict(<function make_default at 0xb7f71e2c>, {0: 42, 1: 'Dead Parrot'})

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Jul 20 '07 #6
On Fri, 20 Jul 2007 19:08:57 +0000, Alex Popescu wrote:
I am wondering what is the most pythonic way of dealing with missing
keys and default values.
[snip three versions]

Others have already mentioned the collections.defaultdict type, however it
seems people have forgotten about the setdefault method of dictionaries.

value = somedict.setdefault(key, defaultvalue)

The disadvantage of setdefault is that the defaultvalue has to be created
up front. The disadvantage of collections.defaultdict is that the "default
factory" function takes no arguments, which makes it rather less than
convenient. One can work around this using global variables:

# The default value is expensive to calculate, and known
# only at runtime.
>>expensivefunction = lambda x: str(x)
D = collections.defaultdict(lambda : expensivefunction(context))
# lots of code goes here...

# set context just before fetching from the default dict
>>context = 42
value = D['key']
print value, D
42 defaultdict(<function <lambdaat 0xb7eb4fb4>, {'key': '42'})

but one should be very leery of relying on global variables like that.

That suggests the best solution is something like this:

def getdefault(adict, key, expensivefunction, context):
if key in adict:
return adict[key]
else:
value = expensivefunction(context)
adict[key] = value
return value

--
Steven.

Jul 21 '07 #7
Can someone who knows about python internals throw some light on why
>>x in dic
is cheaper than
>>dic.has_key(x)
??
Jul 21 '07 #8
On Sat, 21 Jul 2007 09:22:32 +0530, Rustom Mody wrote
Can someone who knows about python internals throw some light on why
>x in dic
is cheaper than
>dic.has_key(x)

??
I won't claim to know Python internals, but compiling and disassembling the
expressions in question reveals the reason:
>>from compiler import compile
from dis import dis
dis(compile("dic.has_key(x)","","eval"))
1 0 LOAD_NAME 0 (dic)
3 LOAD_ATTR 1 (has_key)
6 LOAD_NAME 2 (x)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>>dis(compile("x in dic","","eval"))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (dic)
6 COMPARE_OP 6 (in)
9 RETURN_VALUE

"dic.has_key(x)" goes through an attribute lookup to find the function that
looks for the key. "x in dic" finds the function more directly.

--
Carsten Haese
http://informixdb.sourceforge.net

Jul 21 '07 #9
Alex Popescu a écrit :
Hi all!

I am pretty sure this has been asked a couple of times, but I don't seem
to find it on the archives (Google seems to have a couple of problems
lately).

I am wondering what is the most pythonic way of dealing with missing
keys and default values.

According to my readings one can take the following approaches:

1/ check before (this has a specific name and acronym that I haven't
learnt yet by heart)

if not my_dict.has_key(key):
my_obj = myobject()
my_dict[key] = my_obj
else:
my_obj = my_dict[key]
if key not in my_dict:
my_obj = my_dict[key] = myobject()
else:
my_obj = my_dict[key]
2/ try and react on error (this has also a specific name, but...)

try:
my_obj = my_dict[key]
except AttributeError:
my_obj = myobject()
my_dict[key] = my_obj
cf above for a shortcut...
3/ dict.get usage:

my_obj = my_dict.get(key, myobject())
Note that this last one won't have the same result, since it won't store
my_obj under my_dict[key]. You'd have to use dict.setdefault :

my_obj = my_dict.setdefault(key, myobject())
I am wondering which one is the most recommended way?
It depends on the context. wrt/ 1 and 2, use 1 if you expect that most
of the time, my_dict[key] will not be set, and 2 if you expect that most
of the time, my_dict[key] will be set.
get usage seems
the clearest, but the only problem I see is that I think myobject() is
evaluated at call time,
Myobject will be instanciated each time, yes.
and so if the initialization is expensive you
will probably see surprises.
No "surprise" here, but it can indeed be suboptimal if instanciating
myobject is costly.
Jul 21 '07 #10
Alex Popescu a écrit :
Jakub Stolarski <ja*************@gmail.comwrote in
news:11**********************@k79g2000hse.googlegr oups.com:

>>Version 1 and 2 do different thing than version 3. The latter doesn't
add value to dict.

As it was mentioned before, use:
1 - if you expect that there's no key in dict
2 - if you expect that there is key in dict


I may be missing something
You are.
but I think the 3 approaches are completely
equivalent in terms of functionality.
d = dict()
answer = d.get('answer', 42)
answer in d
=False
Jul 21 '07 #11
Carsten Haese <ca*****@uniqsys.comwrote:
On Sat, 21 Jul 2007 09:22:32 +0530, Rustom Mody wrote
Can someone who knows about python internals throw some light on why
>>x in dic
is cheaper than
>>dic.has_key(x)
??

I won't claim to know Python internals, but compiling and disassembling the
expressions in question reveals the reason:
>from compiler import compile
from dis import dis
dis(compile("dic.has_key(x)","","eval"))
1 0 LOAD_NAME 0 (dic)
3 LOAD_ATTR 1 (has_key)
6 LOAD_NAME 2 (x)
9 CALL_FUNCTION 1
12 RETURN_VALUE
>dis(compile("x in dic","","eval"))
1 0 LOAD_NAME 0 (x)
3 LOAD_NAME 1 (dic)
6 COMPARE_OP 6 (in)
9 RETURN_VALUE

"dic.has_key(x)" goes through an attribute lookup to find the function that
looks for the key. "x in dic" finds the function more directly.
Yup, it's mostly that, as microbenchmarking can confirm:

brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'f(23)'
10000000 loops, best of 3: 0.146 usec per loop
brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' '23 in d'
10000000 loops, best of 3: 0.142 usec per loop
brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'f(23)'
10000000 loops, best of 3: 0.146 usec per loop
brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' '23 in d'
10000000 loops, best of 3: 0.142 usec per loop
brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'd.has_key(23)'
1000000 loops, best of 3: 0.278 usec per loop
brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'd.has_key(23)'
1000000 loops, best of 3: 0.275 usec per loop

the in operator still appears to have a tiny repeatable advantage (about
4 nanoseconds on my laptop) wrt even the hoisted method, but the
non-hoisted method, due to repeated lookup, is almost twice as slow
(over 100 nanoseconds penalty, on my laptop).
Alex
Jul 21 '07 #12
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote in
news:46***********************@news.free.fr:
Alex Popescu a écrit :
>Jakub Stolarski <ja*************@gmail.comwrote in
>
[snip...]
d = dict()
answer = d.get('answer', 42)
answer in d
=False
Thanks. I think to make the 3rd approach completely equivalent I should
have been using d.setdefault(key, myojbect()).

../alex
--
..w( the_mindstorm )p.

Jul 21 '07 #13
"Rustom Mody" <ru*********@gmail.comwrote:
Can someone who knows about python internals throw some light on why
>>>x in dic
is cheaper than
>>>dic.has_key(x)

??
Some special methods are optimised by having a reserved slot in the data
structure used to implement a class. The 'in' operator uses one of these
slots so it can bypass all the overheads of looking up an attribute such as
'has_key'.
Jul 21 '07 #14
On Jul 21, 7:48 am, Duncan Booth <duncan.bo...@invalid.invalidwrote:
"Rustom Mody" <rustompm...@gmail.comwrote:
Can someone who knows about python internals throw some light on why
>>x in dic
is cheaper than
>>dic.has_key(x)
??
>From the 2.6 PEP #361 (looks like dict.has_key is deprecated)
Python 3.0 compatability: ['compatibility'-->someone should use a
spell-checker for 'official' releases]
- warnings were added for the following builtins which no
longer exist in 3.0:
apply, callable, coerce, dict.has_key, execfile, reduce,
reload

Jul 21 '07 #15
On Jul 19, 6:29 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>
Myobject will be instanciated each time, yes.
and so if the initialization is expensive you
will probably see surprises.

No "surprise" here, but it can indeed be suboptimal if instanciating
myobject is costly.
What about this way ?

my_obj = my_dict.get(key) or my_dict.setdefault(key,myobject())

Ciao
G.

Jul 21 '07 #16
On Sat, 21 Jul 2007 16:20:37 -0700, genro wrote:
On Jul 19, 6:29 am, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
>No "surprise" here, but it can indeed be suboptimal if instanciating
myobject is costly.

What about this way ?

my_obj = my_dict.get(key) or my_dict.setdefault(key,myobject())
Reduces the unnecessary instantiation of `myobject` to "false" objects.
May be not good enough.

Ciao,
Marc 'BlackJack' Rintsch
Jul 22 '07 #17
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrote:
>
Instead of doing:
if callable(function): function()

you should do:

try:
function()
except TypeError:
pass
That should work for most uses of callable(), but isn't quite the
same. (What if function() has side-effects, or is expensive, and you
want to determine if it is callable, but not actually call it _now_?)
The replacement for callable(x) is simply hasattr(x, '__call__').
Once upon a time it may have been that functions didn't have a __call__
attribute (I haven't checked back on really old Pythons top see if this
was the case), but these
>Also, what is the replacement of reduce? I think I remember seeing
somewhere that lists comprehension would be (but also remember the
advise that reduce will be quicker).

No, a list comprehension isn't equivalent to reduce(). There is no
replacement for reduce().
<snip>
There are of course several replacements for specialised uses of reduce:
sum, any, all. There is no general purpose replacement, but you can
write one in a few lines if you really need it.
>
It's a shame really. Oh well, maybe it will sneak back in via a
functional module, or itertools, or something. What a waste, what a
waste.
I'm sure it will reappear in some other module, but that's the correct
place for a little used function, not in builtins.
Jul 30 '07 #18
On Mon, 30 Jul 2007 07:37:05 +0000, Duncan Booth wrote:
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrote:
>>
Instead of doing:
if callable(function): function()

you should do:

try:
function()
except TypeError:
pass
That should work for most uses of callable(), but isn't quite the
same. (What if function() has side-effects, or is expensive, and you
want to determine if it is callable, but not actually call it _now_?)

The replacement for callable(x) is simply hasattr(x, '__call__').
Once upon a time it may have been that functions didn't have a __call__
attribute (I haven't checked back on really old Pythons top see if this
was the case), but these
Your sentence seems to have run out early :)

Thanks, I didn't know that -- I remember that Back In The Day checking if
something was callable was tricky, because it could be a function, a
method, or a class with __call__. It makes much more sense to make all
callables go through __call__.
>>Also, what is the replacement of reduce? I think I remember seeing
somewhere that lists comprehension would be (but also remember the
advise that reduce will be quicker).

No, a list comprehension isn't equivalent to reduce(). There is no
replacement for reduce().
<snip>
There are of course several replacements for specialised uses of reduce:
sum, any, all. There is no general purpose replacement, but you can
write one in a few lines if you really need it.
True. But writing the same basic algorithm over and over again is about as
far from best practice as you can get without being a PHP programmer.
*wink* Currying is easy to do too, but Python has grown a function
functools.partial() to do it properly. That's as it should be.

(Yes, I know that's a misuse of the term currying, but it's a common one,
and easier than saying "Making a partial function".)

>It's a shame really. Oh well, maybe it will sneak back in via a
functional module, or itertools, or something. What a waste, what a
waste.

I'm sure it will reappear in some other module, but that's the correct
place for a little used function, not in builtins.
Oh, I would have no problem at all with reduce being banished to the
functtools module. But it's a shame to have to go through the whole PEP
process, and risk Guido saying no.
--
Steven.

Jul 30 '07 #19
Steve Holden <st***@holdenweb.comwrites:
[...]
Yup. Anyway there's a trivial translation for uses of apply.

apply(f, *args, **kw) = f(*args, **kw)
[...]

Steve means:

apply(f, args, kw) = f(*args, **kw)
John
Aug 1 '07 #20
Steven D'Aprano a écrit :
(snip)
Instead of doing:
if callable(function): function()

you should do:

try:
function()
except TypeError:
pass
There are time where you may want to know if you have a callable without
calling it...
That should work for most uses of callable(), but isn't quite the same.
(What if function() has side-effects, or is expensive, and you want to
determine if it is callable, but not actually call it _now_?)
Indeed.

The 'correct' replacement would be:

if hasattr(obj, '__call__'):
# it's a callable

but I don't find it so Pythonic to have to check for a __magic__ method.

>>Also, what is the replacement of reduce? I think I remember seeing
somewhere that lists comprehension would be (but also remember the
advise that reduce will be quicker).


No, a list comprehension isn't equivalent to reduce(). There is no
replacement for reduce().

Guido has essentially done the functional equivalent of deciding that
because he personally doesn't like for loops, they can and should be
written out as:

counter = 0
while counter < len(sequence):
item = sequence[counter]
do_something_with_item
counter += 1

because it is "easier to read" than a for loop.

And yes, if you think my example is extreme because nobody would be that
stupid, that's the point: removing reduce() _is_ that stupid (and it is
not often I say that about a language design decision by Guido!). Python
can, and probably will, get away with it only because reducing an iterable
to a single value is an uncommon operation, and the most common uses of it
(summing a sequence, finding the minimum and maximum) already have
workable replacements.

It's especially stupid because map() and filter(), both of which do have
simple, easy to understand, completely functional replacements, are going
to stay. reduce() doesn't, and it is going. That's nuts.
InMyArms(TM) !

(Guido, if you read us...)
Aug 1 '07 #21
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote in
news:46**********************@news.free.fr:
Steven D'Aprano a écrit :
(snip)
>Instead of doing:
>if callable(function): function()

you should do:

try:
function()
except TypeError:
pass

There are time where you may want to know if you have a callable
without calling it...
>That should work for most uses of callable(), but isn't quite the
same. (What if function() has side-effects, or is expensive, and you
want to determine if it is callable, but not actually call it _now_?)

Indeed.

The 'correct' replacement would be:

if hasattr(obj, '__call__'):
# it's a callable

but I don't find it so Pythonic to have to check for a __magic__
method.

It looks like Python devs have decided it is Pythonic, because it is
already in the PEP. Same for execfile and the others. And I am not
arguing pro or con. I was just wondering about the reasons, as I haven't
been able to find anything (neither here nor on the dev group).

bests,
../alex
--
..w( the_mindstorm )p.

Aug 2 '07 #22
Alex Popescu a écrit :
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote in
news:46**********************@news.free.fr:
(snip)
>if hasattr(obj, '__call__'):
# it's a callable

but I don't find it so Pythonic to have to check for a __magic__
method.

It looks like Python devs have decided it is Pythonic, because it is
already in the PEP.
I do know, and I disagree with this decision.

FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(),
getattr(obj, name) for obj.__getattr__(name), type(obj) for
obj.__class__ etc... IOW, we do have a lot of builtin functions that
mostly encapsulate calls to __magic__ methods, and I definitively don't
understand why this specific one (=callable(obj)) should disappear. I
usually have lot of respect for Guido's talent as a language designer
(obviously since Python is still MFL), but I have to say I find this
particular decision just plain stupid. Sorry.
Aug 2 '07 #23
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
wrote:
Alex Popescu a écrit :
Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote in
news:46**********************@news.free.fr:
(snip)
if hasattr(obj, '__call__'):
# it's a callable

but I don't find it so Pythonic to have to check for a __magic__
method.
It looks like Python devs have decided it is Pythonic, because it is
already in the PEP.

I do know, and I disagree with this decision.

FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(),
getattr(obj, name) for obj.__getattr__(name), type(obj) for
obj.__class__ etc... IOW, we do have a lot of builtin functions that
mostly encapsulate calls to __magic__ methods, and I definitively don't
understand why this specific one (=callable(obj)) should disappear. I
Maybe because it DOESN'T "encapsulate a call" to a magic method, but
rather the mere check for the presence of one?
usually have lot of respect for Guido's talent as a language designer
(obviously since Python is still MFL), but I have to say I find this
particular decision just plain stupid. Sorry.
The mere check of whether an object possesses some important special
method is best accomplished through the abstract-base-classes machinery
(new in Python 3.0: see <http://www.python.org/dev/peps/pep-3119/>). At
this time there is no Callable ABC, but you're welcome to argue for it
on the python-3000 mailing list (please do check the archives and/or
check privately with the PEP owner first to avoid duplication).
Alex

Aug 2 '07 #24
Alex Martelli a écrit :
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
wrote:
>Alex Popescu a écrit :
>>Bruno Desthuilliers <bd*****************@free.quelquepart.frwrote in
news:46**********************@news.free.fr:
(snip)
>>>if hasattr(obj, '__call__'):
# it's a callable

but I don't find it so Pythonic to have to check for a __magic__
method.
It looks like Python devs have decided it is Pythonic, because it is
already in the PEP.
I do know, and I disagree with this decision.

FWIW, repr(obj) is mostly syntactic sugar for obj.__repr__(),
getattr(obj, name) for obj.__getattr__(name), type(obj) for
obj.__class__ etc... IOW, we do have a lot of builtin functions that
mostly encapsulate calls to __magic__ methods, and I definitively don't
understand why this specific one (=callable(obj)) should disappear. I

Maybe because it DOESN'T "encapsulate a call" to a magic method, but
rather the mere check for the presence of one?
Yes, true. But it doesn't make such a big difference IMHO : it's about
decoupling API (the builtin funcs) from implementation (accessing |
calling | checking for the presence of a given implementation attribute).
>usually have lot of respect for Guido's talent as a language designer
(obviously since Python is still MFL), but I have to say I find this
particular decision just plain stupid. Sorry.

The mere check of whether an object possesses some important special
method is best accomplished through the abstract-base-classes machinery
(new in Python 3.0: see <http://www.python.org/dev/peps/pep-3119/>). At
this time there is no Callable ABC, but you're welcome to argue for it
on the python-3000 mailing list (please do check the archives and/or
check privately with the PEP owner first to avoid duplication).
I'll have a look. Thanks for the pointers.
Aug 2 '07 #25
al***@mac.com (Alex Martelli) wrote in news:1i27mku.1sc8l3x1dda3crN%
al***@mac.com:
Bruno Desthuilliers <br********************@wtf.websiteburo.oops.com >
wrote:
>Alex Popescu a écrit :

[... snip ...]
The mere check of whether an object possesses some important special
method is best accomplished through the abstract-base-classes machinery
(new in Python 3.0: see <http://www.python.org/dev/peps/pep-3119/>). At
this time there is no Callable ABC, but you're welcome to argue for it
on the python-3000 mailing list (please do check the archives and/or
check privately with the PEP owner first to avoid duplication).
This PEP sounds very similar to Java interfaces (well, as an enhanced
version as you are allowed to programmatically control this inheritance
chain). Interesting approach. And now I can agree that the removal of
callable() makes sense!

Thanks a lot for the pointer Alex.

../alex
--
..w( the_mindstorm )p.
>
Alex

Aug 2 '07 #26

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Robin Cull | last post by:
Imagine I have a dict looking something like this: myDict = {"key 1": , "key 2": , "key 3": , "key 4": } That is, a set of keys which have a variable length list of associated values after...
6
by: David Rasmussen | last post by:
If I have a collection of dicts like: john = {'id': 1, 'name': "John Cleese", 'year': 1939} graham = {'id': 2, 'name': "Graham Chapman", 'year': 1941} I could store all of them in a list. But...
10
by: Gregory Piñero | last post by:
Hey guys, I thought I'd throw this out there since everyone loves optimization questions (it's true, check out the number of replies to those type of questions!) Right now I have a function...
3
by: David MacKay | last post by:
Dear Greater Py, <motivation note="reading this bit is optional"> I am writing a command-line reader for python. I'm trying to write something with the same brevity as perl's one-liner ...
3
by: aking | last post by:
Dear Python people, im a newbie to python and here...so hello! Im trying to iterate through values in a dictionary so i can find the closest value and then extract the key for that...
16
by: Andy Dingley | last post by:
I'm trying to write rot13, but to do it in a better and more Pythonic style than I'm currrently using. What would you reckon to the following pretty ugly thing? How would you improve it? In...
3
by: james_027 | last post by:
hi, a_dict = {'name':'apple', 'color':'red', 'texture':'smooth', 'shape':'sphere'} is there any difference between .. for key in a_dict: from
20
by: Seongsu Lee | last post by:
Hi, I have a dictionary with million keys. Each value in the dictionary has a list with up to thousand integers. Follow is a simple example with 5 keys. dict = {1: , 2: , 900000: , 900001:...
12
by: Florian Brucker | last post by:
Hi everybody! Given a dictionary, I want to create a clustered version of it, collecting keys that have the same value: {1:, 2:, 3:} That is, generate a new dict which holds for each value...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.