473,756 Members | 5,156 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using the result of type() in a boolean statement?

If I define a dictionary where one or more of the values is also a
dictionary, e.g.:

my_dict={"a":"s tring", "b":"string ", "c":{"x":"0","y ":"1"},
"d":"string "}

How can I use the output of type() so I can do one thing if the value
is a string, and another if the value is a dictionary?

i.e., I'd like to define a loop like this, but I'm not sure of the
syntax:

for key, value in my_dict.items() :
if type{value) is <type 'dict'>:
# do the dictionary logic
elif type(value) is <type 'str'>:
# do the string logic
# etc
Nov 12 '08 #1
2 1384
dpapathanasiou wrote:
If I define a dictionary where one or more of the values is also a
dictionary, e.g.:

my_dict={"a":"s tring", "b":"string ", "c":{"x":"0","y ":"1"},
"d":"string "}

How can I use the output of type() so I can do one thing if the value
is a string, and another if the value is a dictionary?

i.e., I'd like to define a loop like this, but I'm not sure of the
syntax:

for key, value in my_dict.items() :
if type{value) is <type 'dict'>:
if type(v) is dict:
# do the dictionary logic
elif type(value) is <type 'str'>:
.... is str
# do the string logic
For built-in types without a built-in name, either import the types
module or just make one yourself with type().
>>func = type(lambda:1)
func
<class 'function'>
>>bif = type(abs)
bif
<class 'builtin_functi on_or_method'>

For userclass instances, use the userclass.

Terry Jan Reedy
Nov 12 '08 #2
dpapathanasiou wrote:
... I'd like to define a loop like this, ...
for key, value in my_dict.items() :
if type{value) is <type 'dict'>:
# do the dictionary logic
elif type(value) is <type 'str'>:
# do the string logic
# etc
You're searching for "isinstance " (or possibly issubclass)
for key, value in my_dict.items() :
if isinstance(valu e, dict):
# do the dictionary logic
elif isinstance(valu e, str): # use basestring for str & unicode
# do the string logic

Or, if you _must_ use type:
if issubclass(type (value), dict):
# do the dictionary logic
elif issubclass(type (value), str):
# do the string logic
--Scott David Daniels
Sc***********@A cm.Org
Nov 12 '08 #3

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

Similar topics

3
24035
by: Random Person | last post by:
Does anyone know how to use VBA to relink tables between two MS Access databases? We have two databases, one with VBA code and the other with data tables. The tables are referenced by linked tables in the database where the code resides. If we move the database with the data tables to a new directory, the links are no longer valid. I tried to update the links by changing the Connect property and refreshing: Set td = db.TableDefs(0)...
11
6600
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
1
4010
by: Daveyk0 | last post by:
Hello there, I have a front end database that I have recently made very many changes to to allow off-line use. I keep copies of the databases on my hard drive and link to them rather than the live databases on the network. Is there a way, via code, when I get back in-house from being on the road to click a button, and select the backends I want to link to? I would want to delete all the current links and link to the "live"
1
5063
by: Prasad Karunakaran | last post by:
I am using the C# DirectoryEntry class to retrieve the Properties of an user object in the Active Directory. I need to get the First Name and Last Name as properties. I know it is not supported with the ADSI NT Provider and only supported in the LDAP Provider. So given an UserId (UID) how can I read the First Name and Last Name using LDAP Provider. If anybody can help me with a C# sample code it would of great help. Thanks in advance.
18
4350
by: Jen | last post by:
I'm using Microsoft's own VB.NET FTP Example: http://support.microsoft.com/default.aspx?scid=kb;en-us;832679 I can get the program to create directories, change directories, etc., but I can't get it to upload a file to the FTP server. I just get a "Cannot connect to remote server" error after this TRY: s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
6
17205
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived without my handphone BeEPINg for new message ? I read up the AT commands, but when getting down...
1
7742
by: Thiero | last post by:
Hi I posted s thread but did have any reply, I am a new programmer and really wants someone to help me on how to use TreeMap for this code cos I want to it to be able to handle the options from 6 to 9 in the menu of options: /*the next method to be implemented is the method presentResultsToUser() which is expected to print a menu of options on the screen and also will ask the user to choose from that menu*/ public void...
4
3304
by: Tugrul HELVACI | last post by:
Changing DisplayNames of my properties using PropertyGrid component, how ?? I'm using Delphi 2006 and I have a class defination like this: TPerson = class fPersonName : String; fPersonSurName : String; fPersonAge : Integer; published property PersonName : String read fPersonName write fPersonName;
1
2617
by: kommaraju | last post by:
iam a starter to db2 & jdbc.i have a servlet program which connects to ibm db2 using jdbc.when i run this using apache tomcat 4.1.34 , it is showing a error message of HTTP STATUS 500 my jdbc program is as follows import java.sql.*; import java.lang.*; import java.io.*; import java.util.*;
4
5520
by: Marc | last post by:
Hi, I don't get it I cannot get this to work, can somebody give me a hint Table1 contains a field Id which is a GUID as primary key and DATA a string, I want to insert a new row but it does not work. void gv_RowCommand(Object sender, GridViewCommandEventArgs e) { ClientScript.RegisterStartupScript(GetType(), "MyAlert2", "alert('Command=" + e.CommandName + "');", true); if (e.CommandName == "New")
0
9462
marktang
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...
0
9287
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
10046
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
9886
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
9857
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
8723
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...
0
6542
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
5318
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3817
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

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.