473,799 Members | 3,033 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Learning about dictionaries

I'm teaching myself python and in the course of playing around with
dictionaries, I tried to create the following trivial dictionary

{1:'one', 2:'two'}

So I entered
dict(1='one',2= 'two') SyntaxError: keyword can't be an expression

As this did not work, I tried dict(1=one,2=tw o) SyntaxError: keyword can't be an expression

and dict('1'='one', '2'='two') SyntaxError: keyword can't be an expression

as well as dict('1'=one,'2 '=two) SyntaxError: keyword can't be an expression

Out of curiosity, I tried dict(one=1,two= 2) {'two': 2, 'one': 1}

Why does this last attempt work, and more importantly, why did my four
earlier attempts fail? I might add that I have no trouble getting what
I want with dict(zip((1,2), ('one','two'))) {1: 'one', 2: 'two'}
or dict(((1,'one') ,(2,'two')))

{1: 'one', 2: 'two'}

Sincerely

Thomas Philips
Jul 18 '05 #1
4 8371
Thomas Philips wrote:
I'm teaching myself python and in the course of playing around with
dictionaries, I tried to create the following trivial dictionary

{1:'one', 2:'two'}

So I entered
dict(1='one ',2='two')
SyntaxError: keyword can't be an expression

As this did not work, I tried
dict(1=one, 2=two)
SyntaxError: keyword can't be an expression

and
dict('1'='o ne','2'='two')
SyntaxError: keyword can't be an expression

as well as
dict('1'=on e,'2'=two)
SyntaxError: keyword can't be an expression

Out of curiosity, I tried
dict(one=1, two=2)
{'two': 2, 'one': 1}

Why does this last attempt work, and more importantly, why did my four
earlier attempts fail? I might add that I have no trouble getting what
I want with
dict(zip((1 ,2),('one','two ')))
{1: 'one', 2: 'two'}
or
dict(((1,'o ne'),(2,'two')) )
{1: 'one', 2: 'two'}

Sincerely

Thomas Philips

d={1:'one',2:'t wo'}
d {1: 'one', 2: 'two'} dd=dict(d)
dd

{1: 'one', 2: 'two'}
Jul 18 '05 #2
Thomas Philips wrote on Friday 16 April 2004 18:50:
I'm teaching myself python and in the course of playing around with
dictionaries, I tried to create the following trivial dictionary

{1:'one', 2:'two'}

So I entered
dict(1='one',2= 'two') SyntaxError: keyword can't be an expression
Try doing 1 = 'one' in the interactive interpreter. Does it work? Nope. Did
you expect it to work? (Hopefully not :).) So obviously it doesn't work
inside a function call neither.
Out of curiosity, I tried dict(one=1,two= 2) {'two': 2, 'one': 1}


Bingo :). Python has a special construct for functions which accept any
numbers of keyword arguments (these are arguments which have the form of
<name>=<object> , as opposed to non-keyword arguments which are just
<object>). This means that you don't have to specify the parameters in
advance like this:
def myfunc(a, b): .... pass

Instead, you allow any number of parameters to be passed to the function
using '**'
def myfunc(**kwds): .... print kwds
.... # kwds is a dictionary containing all parametername-value pairs
.... myfunc(a='5', b=6, c=True) {'a': '5', 'c': True, 'b': 6}

You can modify myfunc now very easily to behave like dict() in this
particular case:
def myfunc(**kwds): .... return kwds
.... mydict = myfunc(a='5', b=6, c=True)
print mydict

{'a': '5', 'c': True, 'b': 6}

The method Wes specified for creating dictionaries is more useful and usable
IMO than dict() with keyword parameters.

--
Yours,

Andrei

=====
Real contact info (decode with rot13):
ce******@jnanqb b.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
Jul 18 '05 #3
Thomas Philips wrote:
I'm teaching myself python and in the course of playing around with
dictionaries, I tried to create the following trivial dictionary

{1:'one', 2:'two'}
that's a dictionary, right.

(to be precise, it's a "dictionary display" which is how you enter
"dictionary values" in Python source code)
So I entered
dict(1='one',2= 'two')


that's not a dictionary, that's a function call.

you're trying to call a function called "dict" with two keyword arguments,
but your keywords doesn't match Python's identifier syntax.

more here:

http://docs.python.org/ref/calls.html
http://docs.python.org/ref/dict.html

</F>


Jul 18 '05 #4
Thomas Philips wrote:
I'm teaching myself python and in the course of playing around with
dictionaries, I tried to create the following trivial dictionary

{1:'one', 2:'two'}

So I entered
dict(1='one ',2='two')
SyntaxError: keyword can't be an expression

As this did not work, I tried
dict(1=one, 2=two)
SyntaxError: keyword can't be an expression

and
dict('1'='o ne','2'='two')
SyntaxError: keyword can't be an expression

as well as
dict('1'=on e,'2'=two)
SyntaxError: keyword can't be an expression

Out of curiosity, I tried
dict(one=1, two=2)
{'two': 2, 'one': 1}

Why does this last attempt work, and more importantly, why did my four
earlier attempts fail? I might add that I have no trouble getting what
I want with
dict(zip((1 ,2),('one','two ')))
{1: 'one', 2: 'two'}
or
dict(((1,'o ne'),(2,'two')) )
{1: 'one', 2: 'two'}

Sincerely

Thomas Philips

Thomas,
Does this help:
print(dict.__do c__) dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)


wes

Jul 18 '05 #5

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

Similar topics

0
1367
by: Till Plewe | last post by:
Is there a way to speed up killing python from within a python program? Sometimes shutting down takes more than 10 times as much time as the actual running of the program. The programs are fairly simple (searching/organizing large boardgame databases) but use a lot of memory (1-6GB). The memory is mostly used for simple structures like trees or relations. Typically there will be a few large dictionaries and many small...
8
2624
by: Frohnhofer, James | last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a function. I did not want to do def fn(): a = {} b = {} c = {} . . . z = {}
3
2377
by: Shivram U | last post by:
Hi, I want to store dictionaries on disk. I had a look at a few modules like bsddb, shelve etc. However would it be possible for me to do the following hash = where the key is an int and not a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
90
3892
by: Jhon smith | last post by:
Hi all,Just wondering are there any problems with learning c from older books,as I have picked up some from 1988,1994,1997,1998. By using books of this age(Im on a tight budget)am I going to missout on anything in the langauge or has C remaind similar. I intend to use Dev-C++ on the windows platform. If any one feels theres anything I should be aware of,please help me out,I feel a bit lost with all thats out there regarding this language....
210
10566
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
2
2632
by: David Pratt | last post by:
Hi. I like working with lists of dictionaries since order is preserved in a list when I want order and the dictionaries make it explicit what I have got inside them. I find this combination very useful for storing constants especially. Generally I find myself either needing to retrieve the values of constants in an iterative way (as in my contrived example below). Perhaps even more frequent is given one value is to look up the matching...
3
1502
by: Faisal Alquaddoomi | last post by:
Hello, I'm having a bit of trouble isolating my scripts from each other in my embedded Python interpreter, so that their global namespaces don't get all entangled. I've had some luck with PyRun_FileEx(), as you can specify dictionaries to use for the globals and locals, but it seems that you can't do the same for PyEval_CallObject() (which i use for calling the callbacks previously registered by scripts run via PyRun_FileEx()). Is there...
8
1751
by: placid | last post by:
Hi all, Just wondering if anyone knows how to pop up the dialog that windows pops up when copying/moving/deleting files from one directory to another, in python ? Cheers
14
1826
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
9544
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
10490
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...
1
10238
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
10030
tracyyun
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...
0
9077
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
7570
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...
1
4145
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
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.