Hi ng,
what the preferred way for see if the dict has a key?
We have a lot of solutions:
key in dict
key in dict.keys()
dict.has_key(key)
....
but what the better or the more "pythonic"?
Thanks,
Michele 25 2373
Michele Petrazzo wrote: what the preferred way for see if the dict has a key? We have a lot of solutions:
key in dict
new syntax (2.3 and later).
key in dict.keys()
inefficient and pointless.
dict.has_key(key)
old syntax; use for code that needs to be backwards compatible.
but what the better or the more "pythonic"?
see above.
</F>
On Fri, 30 Jun 2006 10:19:46 +0000, Michele Petrazzo wrote: Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions:
key in dict key in dict.keys() dict.has_key(key) ...
but what the better or the more "pythonic"?
Thanks, Michele
It is a religious call....
Fredrik Lundh wrote: Michele Petrazzo wrote:
what the preferred way for see if the dict has a key? We have a lot of solutions:
key in dict
new syntax (2.3 and later).
So, following it, it can be used for the operations like len?
len(dict) -> len(dict.keys()) ?
Thanks,
Michele
Michele Petrazzo wrote: Hi ng, what the preferred way for see if the dict has a key? We have a lot of solutions:
key in dict key in dict.keys() dict.has_key(key) ...
try:
dict[key]
except KeyError:
...
else:
...
but what the better
Depends on the context.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Bruno Desthuilliers wrote: but what the better
Depends on the context.
If know only one context: see if the key are into the dict... What other
context do you know?
Michele
Michele Petrazzo wrote: key in dict new syntax (2.3 and later).
So, following it, it can be used for the operations like len?
what's "it" in this sentence?
len(dict) -> len(dict.keys()) ?
len(dict.keys()) is a lousy way to spell len(dict).
</F>
Fredrik Lundh wrote: Michele Petrazzo wrote:
key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len?
what's "it" in this sentence?
It, is the thought that the new 2.3 introduce.
Michele
Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better
Depends on the context.
If know only one context: see if the key are into the dict... What other context do you know?
Michele
Perhaps Bruno meant this:
try:
... my_dict[key] ...
except:
....
when we expect that the key will most often be in my_dict so that
exception will be raised rarely, otherwise use
if key in dict
André
André wrote: Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better Depends on the context. If know only one context: see if the key are into the dict... What other context do you know?
Michele
Perhaps Bruno meant this:
try: ... my_dict[key] ... except: ....
Yes I see :)
when we expect that the key will most often be in my_dict so that exception will be raised rarely
I didn't thought this because if I think that a key aren't in a dict, I
use dict.get(key, default) otherwise use if key in dict
André
Thanks to all,
Michele
Michele Petrazzo wrote: Bruno Desthuilliers wrote: but what the better
Depends on the context.
If know only one context: see if the key are into the dict... What other context do you know?
Michele
Why do you want to do that ?
if key in dict:
value = dict[key]
else:
value = None
could be write:
try:
value = dict[key]
except KeyError:
value = None
so depends of the context...
Michele Petrazzo wrote: Michele Petrazzo wrote:
> key in dict new syntax (2.3 and later). So, following it, it can be used for the operations like len?
what's "it" in this sentence?
It, is the thought that the new 2.3 introduce.
support for "key in dictionary" form was added in 2.3 (in earlier versions,
"in" was only supported for sequences, not for mappings).
len(dictionary) works in all Python versions.
</F>
"André" wrote: Perhaps Bruno meant this:
try: ... my_dict[key] ... except: ...
when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use
on my machine, "key in dict" is about twice as fast as the full try/getitem con-
struct when the key is present in the dict, so that's not a very good optimization.
now, if the OP had been interested in the associated value, things might have
been a bit different.
</F>
looping wrote: Michele Petrazzo wrote:
Bruno Desthuilliers wrote:
but what the better
Depends on the context.
If know only one context: see if the key are into the dict... What other context do you know?
Why do you want to do that ?
if key in dict: value = dict[key] else: value = None
could be write:
value = dict.get(key, None)
(snip)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Fredrik Lundh wrote: "André" wrote:
Perhaps Bruno meant this:
try: ... my_dict[key] ... except: ...
when we expect that the key will most often be in my_dict so that exception will be raised rarely, otherwise use
on my machine, "key in dict" is about twice as fast as the full try/getitem con- struct when the key is present in the dict,
Doesn't it depends on the number of keys in the dict ?
so that's not a very good optimization.
FWIW, I personaly didn't meant to present it as an optimisation - just
as one more possible way to test the existence of a given key...
now, if the OP had been interested in the associated value, things might have been a bit different.
</F>
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Bruno Desthuilliers wrote: looping wrote: Michele Petrazzo wrote:
Bruno Desthuilliers wrote:
>but what the better
Depends on the context.
If know only one context: see if the key are into the dict... What other context do you know?
Why do you want to do that ?
if key in dict: value = dict[key] else: value = None
could be write:
value = dict.get(key, None)
value = dict.get(key)
;)
Georg
"Michele Petrazzo" <mi**************@TOGLIunipex.it> wrote in message
news:zZ********************@twister1.libero.it... when we expect that the key will most often be in my_dict so that exception will be raised rarely
I didn't thought this because if I think that a key aren't in a dict, I use dict.get(key, default)
Another factor to consider is if "default" is not something simple like 0 or
None, but is an object constructed and initialized with some expensive
initialization code (like access to a database). In this case:
dict.get(key, ExpensiveObjectToCreate())
always creates the default value, and if the key does not exist, then
promptly drops it on the floor.
In such a case you'd be better off with one of the "check for existence"
patterns, which only creates the default value if you *know* you're going to
need it.
-- Paul
Bruno Desthuilliers wrote: on my machine, "key in dict" is about twice as fast as the full try/getitem construct when the key is present in the dict,
Doesn't it depends on the number of keys in the dict ?
why would it depend on the number of keys in the dict ?
</F>
Paul McGuire wrote: Another factor to consider is if "default" is not something simple like 0 or None, but is an object constructed and initialized with some expensive initialization code (like access to a database). In this case:
dict.get(key, ExpensiveObjectToCreate())
always creates the default value, and if the key does not exist, then promptly drops it on the floor.
In such a case you'd be better off with one of the "check for existence" patterns, which only creates the default value if you *know* you're going to need it.
unless you're targeting 2.5 or later, in which case you can use the
defaultdict class: import collections
def ExpensiveObjectToCreate():
.... print "creating an expensive object"
.... return "expensive object"
.... d = collections.defaultdict(ExpensiveObjectToCreate) d["key"]
creating an expensive object
'expensive object' d["key"]
'expensive object'
or, if you prefer, the new __missing__ hook:
class mydict(dict):
.... def __missing__(self, key):
.... print "add new object base on", key
.... value = "new object"
.... self[key] = value
.... return value
.... d = mydict() d["key"]
add new object base on key
'new object' d["key"]
'new object'
</F>
Fredrik Lundh wrote: Bruno Desthuilliers wrote:
on my machine, "key in dict" is about twice as fast as the full try/getitem construct when the key is present in the dict,
Doesn't it depends on the number of keys in the dict ?
why would it depend on the number of keys in the dict ?
</F>
Seems that if "key in dict" do a simple linear search, it depends on the
number of keys in dict (and the position of the searched key etc...).
And if I'm missing the point and you it and you know why, it would be
simple to explain than to answer my question with another question.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Georg Brandl wrote: Bruno Desthuilliers wrote:
looping wrote:
Michele Petrazzo wrote:
Bruno Desthuilliers wrote:
>> but what the better > > > Depends on the context. >
If know only one context: see if the key are into the dict... What other context do you know?
Why do you want to do that ?
if key in dict: value = dict[key] else: value = None
could be write:
value = dict.get(key, None)
value = dict.get(key)
Yes - but :
1/ not everybody knows that dict.get() takes a second optional param.
Note that, while it happens that the default return value of dict.get()
is the same as in the above example, but it may not have been the case.
2/ Since dict.get() implicitely returns None while getattr() defaults to
raising an AttributeError unless you provide a default, I prefer to be
very explicit when using dict.get().
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Fredrik Lundh <fr*****@pythonware.com> wrote: Michele Petrazzo wrote:
what the preferred way for see if the dict has a key? We have a lot of solutions:
key in dict
new syntax (2.3 and later).
Fine with Python 2.2 as well, actually -- so, "new" only in an
_extremely_ loose sense of the word:-).
Alex
Bruno Desthuilliers wrote: Fredrik Lundh wrote: Bruno Desthuilliers wrote:
on my machine, "key in dict" is about twice as fast as the full
try/getitem construct when the key is present in the dict,
Doesn't it depends on the number of keys in the dict ?
why would it depend on the number of keys in the dict ?
</F>
Seems that if "key in dict" do a simple linear search, it depends on the number of keys in dict (and the position of the searched key etc...).
And if I'm missing the point and you it and you know why, it would be simple to explain than to answer my question with another question.
maybee we can imagine that key in dict
just perform
try:
dict[key]
return True
except KeyError:
return False
If I understand correctly, it will be time constant no ??
just the needed time to compute the hash for the key
Eric
Fredrik Lundh wrote: Bruno Desthuilliers wrote:
Seems that if "key in dict" do a simple linear search
that would be rather silly.
hint: http://pyref.infogami.com/__contains__
Of course. It's just me being silly...
:(
Thanks F
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Bruno Desthuilliers wrote: value = dict.get(key, None)
value = dict.get(key)
Yes - but : 1/ not everybody knows that dict.get() takes a second optional param. Note that, while it happens that the default return value of dict.get() is the same as in the above example, but it may not have been the case.
2/ Since dict.get() implicitely returns None while getattr() defaults to raising an AttributeError unless you provide a default, I prefer to be very explicit when using dict.get().
You're right, and I would write that with explicit None too.
Just wanted to continue the shortening ;)
Georg This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
by: GrelEns |
last post by:
hello,
i would like if this behaviour can be obtained from python : trap an
attributeError from inside a subclassing dict class... (here is a silly
examples to explain my question)
class...
|
by: Bengt Richter |
last post by:
Has anyone found a way besides not deriving from dict?
Shouldn't there be a way?
TIA
(need this for what I hope is an improvement on the Larosa/Foord OrderedDict ;-)
I guess I can just document...
|
by: sandravandale |
last post by:
I can think of several messy ways of making a dict that sets a flag if
it's been altered, but I have a hunch that experienced python
programmers would probably have an easier (well maybe more...
|
by: Cruella DeVille |
last post by:
I'm trying to implement a bookmark-url program, which accepts user
input and puts the strings in a dictionary. Somehow I'm not able to
iterate myDictionary of type Dict{}
When I write print...
|
by: George Sakkis |
last post by:
Although I consider dict(**kwds) as one of the few unfortunate design
choices in python since it prevents the future addition of useful
keyword arguments (e.g a default value or an orderby...
|
by: jeremito |
last post by:
Please excuse me if this is obvious to others, but I can't figure it
out. I am subclassing dict, but want to prevent direct changing of
some key/value pairs. For this I thought I should override...
|
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
|
by: |
last post by:
Hello all,
I have a question which might be simple or need some work around.
I want to do something like this. My class/instance has a dict as a
property. I want the instance to catch the...
|
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:...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
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
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
| |