473,390 Members | 936 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,390 software developers and data experts.

a dict trick

hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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

Aug 2 '07 #1
8 2101
On Thu, 02 Aug 2007 06:32:11 +0000, james_027 wrote:
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}
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.html#l2h-294>` for more information on
`dict` methods.

Or you could use the `collections.defaultdict <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(lambda:'unknown', d)
d2['name']
'james'
>>d2['sex']
'unknown'

HTH,
Stargaming

Aug 2 '07 #2
james_027 wrote:
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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

Aug 2 '07 #3
james_027 wrote:
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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(key, default_value)
Aug 2 '07 #4
james_027 <ca********@gmail.comwrote in news:1186036331.304916.304020
@e9g2000prf.googlegroups.com:
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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

Aug 2 '07 #5
Hi,

what if we're not dealing with dict? is there a pythonic way of doing
ternary? the bool ? x:y

Thanks
james

Aug 2 '07 #6
james_027 a écrit :
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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':'english'}
d.get('sex', 'unknown')

Aug 2 '07 #7
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.
Aug 2 '07 #8
In article <11**********************@e9g2000prf.googlegroups. com>,
james_027 <ca********@gmail.comwrote:
hi

for example I have this dictionary

dict = {'name':'james', 'language':'english'}

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('sex', '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
Aug 2 '07 #9

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...
17
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...
1
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 :...
3
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...
11
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...
15
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...
12
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...
4
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: ...
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: 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...
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...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
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...

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.