473,597 Members | 2,392 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Append a new value to dict

Pat
I know it's not "fair" to compare language features, but it seems to me
(a Python newbie) that appending a new key/value to a dict in Python is
awfully cumbersome.

In Python, this is the best code I could come up with for adding a new
key, value to a dict

mytable.setdefa ult( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;

Is there a better/easier way to code this in Python than the
obtuse/arcane setdefault code?
Oct 13 '08 #1
20 3056
Pat
Pat wrote:
I know it's not "fair" to compare language features, but it seems to me
(a Python newbie) that appending a new key/value to a dict in Python is
awfully cumbersome.

In Python, this is the best code I could come up with for adding a new
key, value to a dict

mytable.setdefa ult( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;

Is there a better/easier way to code this in Python than the
obtuse/arcane setdefault code?
Naturally, right after writing my post I found that there is an easier way:

table[ k ] = v

I found that in "Python for Dummies". How apropos.
Oct 13 '08 #2
jdd
On Oct 13, 7:21*am, Pat <P...@junk.comw rote:
Is there a better/easier way to code this in Python than the
obtuse/arcane setdefault code?
foo = {'bar': 'baz'}
foo.update({'qu ux': 'blah'})
Oct 13 '08 #3
Pat schrieb:
I know it's not "fair" to compare language features, but it seems to me
(a Python newbie) that appending a new key/value to a dict in Python is
awfully cumbersome.

In Python, this is the best code I could come up with for adding a new
key, value to a dict

mytable.setdefa ult( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;
Whats wrong with:

mytable[key] = value

cheers
Paul

Oct 13 '08 #4
Pat wrote:
I know it's not "fair" to compare language features, but it seems to me
(a Python newbie) that appending a new key/value to a dict in Python is
awfully cumbersome.

In Python, this is the best code I could come up with for adding a new
key, value to a dict

mytable.setdefa ult( k, [] ).append( v )

In Perl, the code looks like this:

$h{ $key } = $value ;
There's a huge difference here:

In your Python example you're using a list. In the Perl example you're
using a scalar value.

Is there a better/easier way to code this in Python than the
obtuse/arcane setdefault code?
When just assigning a new key-value-pair there's no problem in Python.
(Just refer to the answers before.) When I switched from Perl to Python
however I commonly ran into this problem:
>>counter = {}
counter['A'] = 1
counter['A'] += 1
counter['A']
2

Ok - assigning a key-value-pair works fine. Incrementing works as well.
>>counter['B'] += 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'B'

However incrementing a non-existing key throws an exception. So you
either have to use a workaround:
>>try:
.... counter['B'] += 1
.... except KeyError:
.... counter['B'] = 1

Since this looks ugly somebody invented the setdefault method:
>>counter['B'] = counter.setdefa ult('B',0) + 1
And this works with lists/arrays as well. When there's no list yet
setdefault will create an empty list and append the first value.
Otherwise it will just append.

Greetings from Vienna,
mathias
Oct 13 '08 #5
>In Python, this is the best code I could come up with for
>adding a new key, value to a dict

mytable.setdef ault( k, [] ).append( v )

Naturally, right after writing my post I found that there is
an easier way:

table[ k ] = v
Just to be clear...these do two VERY different things:
>>v1=42
table1={}
k='foo'
table1.setdef ault(k,[]).append(v1)
table2={}
table2[k]=v1
table1, table2
({'foo': [42]}, {'foo': 42})

Note that the value in the first case is a *list* while the
value in the 2nd case, the value is a scalar. These differ in
the behavior (continuing from above):
>>v2='Second value'
table1.setdef ault(k,[]).append(v2)
table2[k]=v2
table1, table2
({'foo': [42, 'Second value']}, {'foo': 'Second value'})

Note that table1 now has *two* values associated with 'foo',
while table2 only has the most recently assigned value.

Choose according to your use-case. For some of my ETL &
data-processing work, I often want the

mydict.setdefau lt(key, []).append(value)

version to accrue values associated with a given unique key.

-tkc


Oct 13 '08 #6
jdd:
foo = {'bar': 'baz'}
foo.update({'qu ux': 'blah'})
That creates a new dict, to throw it away. Don't do that. Use the
standard and more readable syntax:
foo = {...}
foo['quux'] = 'blah'
Bye,
bearophile
Oct 13 '08 #7
On Mon, 13 Oct 2008 14:10:43 +0200, Mathias Frey wrote:
However incrementing a non-existing key throws an exception. So you
either have to use a workaround:
>>try:
... counter['B'] += 1
... except KeyError:
... counter['B'] = 1

Since this looks ugly somebody invented the setdefault method:
>>counter['B'] = counter.setdefa ult('B',0) + 1
Nope, for this use case there is the `dict.get()` method:

counter['B'] = counter.get('B' , 0) + 1

This assigns only *once* to ``counter['B']`` in every case.

`dict.setdefaul t()` is for situations where you really want to actually
put the initial value into the dictionary, like with the list example by
the OP.

Ciao,
Marc 'BlackJack' Rintsch
Oct 13 '08 #8
be************@ lycos.com a écrit :
jdd:
>foo = {'bar': 'baz'}
foo.update({'q uux': 'blah'})

That creates a new dict, to throw it away.
Just to make it clear for the easily confused ones (like me...):
bearophile is talking about the dict passed as an argument to foo.update
- not about the behaviour of dict.update itself (which of course
modifies the dict in place) !-)

Oct 13 '08 #9
At 2008-10-13T13:14:15Z, be************@ lycos.com writes:
jdd:
>foo = {'bar': 'baz'}
foo.update({'q uux': 'blah'})

That creates a new dict, to throw it away. Don't do that.
I use that if I'm changing many values at once, eg:

foo.update({
'quux': 'blah',
'baz' : 'bearophile',
'jdd' : 'dict',
})

instead of:

foo['quux'] = 'blah'
foo['baz'] = 'bearophile'
foo['jdd'] = 'dict'

because it seems to more clearly indicate what I'm doing, and has fewer
opportunities for types. Still, there is a performance penalty. Running
"my way" 10,000,000 times took 8.7s, and "your way" only took 4.7s. If
you're doing this in an inner loop, that may be significant. While we're on
the subject, use keyword arguments to dict like:

foo.update(dict (quux='blah', baz='bearophile ', jdd='dict'))

was *much* slower, at 11.8s.
--
Kirk Strauser
The Day Companies
Oct 13 '08 #10

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

Similar topics

14
24086
by: tertius | last post by:
Is there a better way to append certain chars in a string with a backslash that the example below? chr = "#$%^&_{}" # special chars to look out for str = "123 45^ & 00 0_" # string to convert n = "" # init new string for i in str: if i in chr: # if special character in str n+='\\' # append it with a backslash n+=i
6
1513
by: M. Clift | last post by:
Hi All, I have tried to come up with a way to do this myself and all I end up with is very long code. What I have is a say item1, item4, item2, item1 etc... What I want to do is append to each item an extra value depending on the previous item.
1
1669
by: Yereth | last post by:
Hi again, still working on my xslt program and I ran into another problem. There is a file which a contains the following structure: <key>1</key> <dict>         ... </dict> <key>2</key>
25
7584
by: Yves Glodt | last post by:
Hello, if I do this: for row in sqlsth: ________pkcolumns.append(row.strip()) ________etc without a prior:
2
2955
by: tonci.tomic | last post by:
I have IDictionary with integers as keys and values. Suppose I want to set value for key=42 to 1 if entry doesn't exist in container. Otherwise, I want to increment value. I ended with: IDictionary dict; .... dict.Add(42, 0); // does nothing if entry exist int val = (int)dict; ++val; dict = val;
11
10554
by: Yves Glodt | last post by:
Hi there, I seem to be unable to find a way to appends more keys/values to the end of a dictionary... how can I do that? E.g: mydict = {'a':'1'} I need to append 'b':'2' to it to have:
6
6096
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or more minutes. 'REMOVE DUBLICATED VALUE FROM ARRAY +++++++++++++++++ Dim col As New Scripting.Dictionary Dim ii As Integer = 0
10
2106
by: HYRY | last post by:
I have the following questions, I am using Python 2.4.2 19167152 #1 11306608 #1 1. the address of a.append and list.append is different, can I get the address of list.append from a.append? 19162720
20
2408
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: ,
0
7883
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,...
0
8263
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8379
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 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...
1
8021
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,...
0
6677
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5842
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5421
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();...
0
3917
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1226
bsmnconsultancy
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...

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.