473,804 Members | 3,603 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checking if a variable is a dictionary


Hello,

This is my first post here. I'm getting my feet wet with Python and I
need to know how can I check whether a variable is of type dictionary.

Something like this:

if isdict(a) then print "a is a dictionary"

Regards,

Guillermo
Mar 6 '08 #1
7 79267
Sam
Hello

if type(a) is dict:
print "a is a dictionnary!"

++

Sam
Mar 6 '08 #2
En Thu, 06 Mar 2008 10:10:47 -0200, Guillermo
<gu************ **@googlemail.c omescribi�:
This is my first post here. I'm getting my feet wet with Python and I
need to know how can I check whether a variable is of type dictionary.

Something like this:

if isdict(a) then print "a is a dictionary"
if isinstance(a, dict): ...

But note that it's more common in Python to try to use it in the intended
way, and catch the possible errors.
Look for "duck typing" in this group, and the difference between "easier
to ask forgiveness
than permission" and "look before you leap".

--
Gabriel Genellina

Mar 6 '08 #3
On Mar 6, 7:10 am, Guillermo <guillermo.lis. ..@googlemail.c omwrote:
Hello,

This is my first post here. I'm getting my feet wet with Python and I
need to know how can I check whether a variable is of type dictionary.

Something like this:

if isdict(a) then print "a is a dictionary"

Regards,

Guillermo
Or

if type(a)==type({ }):
print 'a is a dictionary'
Mar 6 '08 #4
You can also get the dynamic polymorphism without invoking inheritance
by specifying a protocol that the values in your dict must implement,
instead. Protocols are plentiful in Python, perhaps more popular than
type hierarchies.
I'm used to languages with stricter rules than Python. I've read a bit
about Python protocols, but where could I get some more info on
implementation details? Sounds very interesting.

Regards,

Guillermo
Mar 6 '08 #5
On Thu, Mar 6, 2008 at 12:17 PM, Guillermo
<gu************ **@googlemail.c omwrote:
You can also get the dynamic polymorphism without invoking inheritance
by specifying a protocol that the values in your dict must implement,
instead. Protocols are plentiful in Python, perhaps more popular than
type hierarchies.

I'm used to languages with stricter rules than Python. I've read a bit
about Python protocols, but where could I get some more info on
implementation details? Sounds very interesting.
A protocol is just an interface that an object agrees to implement. In
your case, you would state that every object stored in your special
dict must implement the to_tagged_value method with certain agreeable
semantics.

Python implements sequence types, mapping types, iterators, file
streams, and other things with protocols.

For example, iterators must support the "next" and and "__iter__" methods.

Using a protocol instead instead of a type hierarchy requires less
boring boilerplate, and I suppose in Python will usuallly be
preferable except when you want to inherit implementation as well as
interface. In that case, inheritance often saves boilerplate cide
rather than increases it.

It's also misnomered as duck-typing (clearly it should be nomed quack-typing).

--
Neil Cerutti <mr************ ***@gmail.com>
Mar 6 '08 #6

Mamma mia! My head just exploded. I've seen the light.

So you only need to ·want· to have a protocol? That's amazing... Far
beyond the claim that Python is easy. You define protocols in writing
basically! Even my grandma could have her own Python protocol.

Okay, so I think I know where's the catch now -- you must rely on the
fact that the protocol is implemented, there's no way to enforce it if
you're expecting a parrot-like object. You'd try to call the speak()
method and deal with the error if there's no such method?

Thanks a lot!

Guillermo
Mar 9 '08 #7
On Mon, 10 Mar 2008 14:29:48 +0000, Andrew Koenig wrote:
So the question you need to answer is whether you want to determine
whether an object is exactly of type dict, or whether it you are willing
to accept types derived from dict also.
Or other mappings that don't inherit from dict but behave just like
dicts, such as UserDict.
--
Steven
Mar 10 '08 #8

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

Similar topics

5
7921
by: Tesla | last post by:
Hey guys, I want to PHP to do stuff only if a sertain form variable exists. How do i check to see if a variable exists or not? Something like If $http_post_vars exists, then do this. syntax please? :)
2
17406
by: Jonathan | last post by:
I'm puzzled by Python's behavior when binding local variables which are introduced within exec() or execfile() statements. First, consider this simple Python program: # main.py def f() : x = 1 print "x:", x f()
16
2074
by: Ling Lee | last post by:
Hello. I'm trying to write a small program that lets you put in a number as an integer and then it tells you the textuel representation of the number. Like if your input is 42, it will say four two. I found out that I have to make a dictionary like this: List = { 1:"one", 2:"two" and so on )
84
5968
by: Andy Glew | last post by:
I am in search of any rigourous, scientific, academic or industrial studies comparing naming conventions in C++ or similar languages such as Ada: Specifically, are names formed with underscores more or less readable than names formed with MixedCase StudlyCaps camelCase?
134
7925
by: James A. Donald | last post by:
I am contemplating getting into Python, which is used by engineers I admire - google and Bram Cohen, but was horrified to read "no variable or argument declarations are necessary." Surely that means that if I misspell a variable name, my program will mysteriously fail to work with no error message. If you don't declare variables, you can inadvertently re-use an variable used in an enclosing context when you don't intend to, or
10
2004
by: Fredrik Tolf | last post by:
If I have a variable which points to a function, can I check if certain argument list matches what the function wants before or when calling it? Currently, I'm trying to catch a TypeError when calling the function (since that is what is raised when trying to call it with an illegal list), but that has the rather undesirable side effect of also catching any TypeErrors raised inside the function. Is there a way to avoid that? Fredrik Tolf
8
1832
by: Steph | last post by:
Hello, i tried to convert my code php into c#, but no hope... $foo = 'test'; $test = "hello world"; echo ${ $foo }; what is the equivalent in c# language ? thx
0
1385
by: Gabriel Genellina | last post by:
En Fri, 18 Apr 2008 12:23:08 -0300, Shawn Milochik <Shawn@Milochik.comescribió: A dictionary with keys is perfectly reasonable. But a *list* of values has to be searched linearly for every value: a O(n) process. As your friend suggested, searching a dictionary requires O(1) time. A set is even better in this case, because you don't have any use for the values in the inner dictionary (sets and dictionaries are very similar in the...
1
4173
by: GVDC | last post by:
Example server-side JavaScript Web script, Dictionary class //Dictionary class, hash array unlimited length configurable speed/efficiency // printf("<html><body>"); printf("<b>Creating dictionary</b><br\n>"); var dictobj = new Dictionary(5); //dictionary class
0
9589
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
10593
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
10340
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
10329
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,...
1
7626
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
6858
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();...
1
4304
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
3830
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3000
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.