hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
THanks
james 8 2125
On Thu, 02 Aug 2007 06:32:11 +0000, james_027 wrote:
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
First of all, this is a bad name because it shadows (overwrites) the
reference to the builtin constructor, `dict`.
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
If you're using using Python 2.5, you could do this without `and`/`or`
trickery::
>>d['name'] if 'name' in d else 'unknown'
'james'
>>d['sex'] if 'sex' in d else 'unknown'
'unknown'
But there are more elegant ways. For example, the `get` method::
>>d.get('name ', 'unknown')
'james'
>>d.get('sex' , 'unknown')
'unknown'
See the `Python Library Reference, 3.8: Mapping types <http://
docs.python.org/lib/typesmapping.ht ml#l2h-294>` for more information on
`dict` methods.
Or you could use the `collections.de faultdict < http://docs.python.org/lib/
defaultdict-objects.html>` type (new in 2.5, too), which I consider most
elegant::
>>from collections import defaultdict d2 = defaultdict(lam bda:'unknown', d) d2['name']
'james'
>>d2['sex']
'unknown'
HTH,
Stargaming
james_027 wrote:
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
THanks
james
This fails if 'sex' is in the dictionary and it's value happens to be
any of the values that evaluate to a boolean False. In that case you'll
get 'unknow' even though the key is in the dictionary.
However, python dictionaries provide a way to do this:
dict.get('sex', 'unknown')
looks up the value associated with the key if it exists, otherwise it
returns the provided default value.
You may also want to checkout the dictionary method setdefault which has
the functionality of get PLUS if the key is not found, it adds the
key,value pair to the dictionary.
Gary Herron
james_027 wrote:
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
THanks
james
value = your_dict.get(k ey, default_value)
james_027 <ca********@gma il.comwrote in news:1186036331 .304916.304020
@e9g2000prf.goo glegroups.com:
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
THanks
james
Same question discussed at large not far ago:
subject: "Pythonic way of missing dict keys" [1]
bests,
../alex
--
..w( the_mindstorm )p.
[1] http://groups.google.com/group/comp..../thread/175eb4
5909a05a18
Hi,
what if we're not dealing with dict? is there a pythonic way of doing
ternary? the bool ? x:y
Thanks
james
james_027 a écrit :
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one?
No. The first problem is that using 'dict' as an identifier, you're
shadowing the builtin dict type. The second problem is that you're
reinventing the square wheel.
I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
d = {'name':'james' , 'language':'eng lish'}
d.get('sex', 'unknown')
james_027 a écrit :
Hi,
what if we're not dealing with dict? is there a pythonic way of doing
ternary? the bool ? x:y
Python 2.5 introduced the following syntax:
expr1 if condition else expr2
In older Python versions, one has to use and/or (like you wrongly did)
or tuple/dict dispatch or other ad-hoc tricks. Or use a plain old
if/else branch.
In article <11************ **********@e9g2 000prf.googlegr oups.com>,
james_027 <ca********@gma il.comwrote:
hi
for example I have this dictionary
dict = {'name':'james' , 'language':'eng lish'}
value = 'sex' in dict and dict['sex'] or 'unknown'
is a right pythonic of doing this one? I am trying to get a value from
the dict, but if the key doesn't exist I will provide one.
Hi, James,
You might prefer:
d = {'name': 'James', 'language': 'English'}
value = d.get('sex', 'unknown')
This accomplishes what your above code does, using a method of the
built-in dict object.
If you also wish to ADD the new value to the dictionary, you may also
use the following:
value = d.setdefault('s ex', 'unknown')
This returns the same value as the above, but also adds the key 'sex' to
the dictionary as a side-effect, with value 'unknown'.
Cheers,
-M
--
Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA 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 them. What I want to do is filter out a subset of this
dict to produce another dict that satisfies a set of criteria (in this
case whether it contains all four values) to end up with something
|
by: Pierre Fortin |
last post by:
Hi,
Is the following a reasonable generic approach for converting python
returned tuples/lists into dicts...? I'm not advocating library functions
also return dicts (I'd probably spend more time looking up the real
names... :) I'm just looking to make my code more readable and
self-documenting...
--------
|
by: Alexander Kervero |
last post by:
Hi ,today i was reading diveinto python book,in chapter 5 it has a very
generic module to get file information,html,mp3s ,etc.
The code of the example is here :
http://diveintopython.org/object_oriented_framework/index.html
One thing that i have some doubs is this part :
class FileInfo(UserDict):
"store file metadata"
|
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 that you have to spell it dict(d.items()), but I'd
like to hide the internal shenanigans ;-)
Regards,
Bengt Richter
|
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 Pythonic)
way of doing this.
It's important that I can read the contents of the dict without
flagging it as modified, but I want it to set the flag the moment I add
a new element or alter an existing one (the values in the dict are
mutable), this...
| |
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 function), I've
been finding myself lately using it sometimes instead of dict literals,
for no particular reason. Is there any coding style consensus on when
should dict literals be preferred over dict(**kwds) and vice versa ?
George
|
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 the
__setitem__ method as such:
class xs(dict):
"""
XS is a container object to hold information about cross sections.
"""
|
by: Mike P |
last post by:
Hi All,
I have two dictionaries e.g
dict1 = {123:3,234:5,456:3}
dict2 = {123:4,157:2,234:5,456:3,567:2}
I want to merge these two dictionaries together so i have a resultant
dictionary of:
dict3 = {123:,157:,234:,456:,567:}
|
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 of the old dict
a list of the keys of the old dict that have that very value.
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |