472,331 Members | 1,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,331 software developers and data experts.

How to check is something is a list or a dictionary or a string?

Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)
where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?
Thanks,
Rajat
Aug 29 '08 #1
6 2894
On Aug 29, 9:16*am, dudeja.ra...@gmail.com wrote:
Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
* * * * * * self.cbAnalysisLibVersion(END, item)

where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?

Thanks,
Rajat
type() and probably you want to import the types library as well.

In [1]: import types

In [2]: a = {1: {}, False: [], 'yes': False, None: 'HELLO'}

In [3]: a.values()
Out[3]: [[], {}, False, 'HELLO']

In [4]: [type(item) for item in a.itervalues()]
Out[4]: [<type 'list'>, <type 'dict'>, <type 'bool'>, <type 'str'>]

In [6]: for item in a.itervalues():
...: if type(item) is types.BooleanType:
...: print "Boolean", item
...: elif type(item) is types.ListType:
...: print "List", item
...: elif type(item) is types.StringType:
...: print "String", item
...: else:
...: print "Some other type", type(item), ':', item
...:
...:
List []
Some other type <type 'dict': {}
Boolean False
String HELLO
Aug 29 '08 #2
On Aug 29, 12:16 pm, dudeja.ra...@gmail.com wrote:
Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)

where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?
if isinstance(item,basestring):
# it's a string
...
else: # it should be a list
# typically you don't have to check it explicitly;
# even if it's not a list, it will raise an exception later anyway
if you call a list-specific method
HTH,
George
Aug 29 '08 #3
George Sakkis wrote:
On Aug 29, 12:16 pm, dudeja.ra...@gmail.com wrote:
>Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)

where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?

if isinstance(item,basestring):
# it's a string
...
else: # it should be a list
# typically you don't have to check it explicitly;
# even if it's not a list, it will raise an exception later anyway
if you call a list-specific method
HTH,
George
For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings
identically to byte strings. However, you need to be careful in your own
code when testing to see if an object is a string. Do not do this:

if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings
Aug 30 '08 #4
But this changes with Python 3, right?

On Aug 30, 7:15*am, Ken Starks <stra...@lampsacos.demon.co.ukwrote:
George Sakkis wrote:
On Aug 29, 12:16 pm, dudeja.ra...@gmail.com wrote:
Hi,
How to check if something is a list or a dictionary or just a string?
Eg:
for item in self.__libVerDict.itervalues():
* * * * * * self.cbAnalysisLibVersion(END, item)
where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?
if isinstance(item,basestring):
* *# it's a string
* * ...
else: # it should be a list
* *# typically you don't have to check it explicitly;
* *# even if it's not a list, it will raise an exception later anyway
if you call a list-specific method
HTH,
George

For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings
identically to byte strings. However, you need to be careful in your own
code when testing to see if an object is a string. Do not do this:

if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings
Aug 30 '08 #5
josh logan wrote:
But this changes with Python 3, right?
right!

see
http://docs.python.org/dev/3.0/whatsnew/3.0.html

(quote)
Strings and Bytes

* There is only one string type; its name is str but its behavior
and implementation are like unicode in 2.x.
* The basestring superclass has been removed. The 2to3 tool
replaces every occurrence of basestring with str.
* PEP 3137: There is a new type, bytes, to represent binary data
(and encoded text, which is treated as binary data until you decide to
decode it). The str and bytes types cannot be mixed; you must always
explicitly convert between them, using the str.encode() (str -bytes)
or bytes.decode() (bytes -str) methods.
* All backslashes in raw strings are interpreted literally. This
means that Unicode escapes are not treated specially.

* PEP 3112: Bytes literals, e.g. b"abc", create bytes instances.
* PEP 3120: UTF-8 default source encoding.
* PEP 3131: Non-ASCII identifiers. (However, the standard library
remains ASCII-only with the exception of contributor names in comments.)
* PEP 3116: New I/O Implementation. The API is nearly 100%
backwards compatible, but completely reimplemented (currently mostly in
Python). Also, binary files use bytes instead of strings.
* The StringIO and cStringIO modules are gone. Instead, import
io.StringIO or io.BytesIO.
* '\U' and '\u' escapes in raw strings are not treated specially.

On Aug 30, 7:15 am, Ken Starks <stra...@lampsacos.demon.co.ukwrote:
>George Sakkis wrote:
>>On Aug 29, 12:16 pm, dudeja.ra...@gmail.com wrote:
Hi,
How to check if something is a list or a dictionary or just a string?
Eg:
for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)
where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?
if isinstance(item,basestring):
# it's a string
...
else: # it should be a list
# typically you don't have to check it explicitly;
# even if it's not a list, it will raise an exception later anyway
if you call a list-specific method
HTH,
George
For a bit more explanation see, for example,

http://evanjones.ca/python-utf8.html

(Quote)
Working With Unicode Strings

Thankfully, everything in Python is supposed to treat Unicode strings
identically to byte strings. However, you need to be careful in your own
code when testing to see if an object is a string. Do not do this:

if isinstance( s, str ): # BAD: Not true for Unicode strings!

Instead, use the generic string base class, basestring:

if isinstance( s, basestring ): # True for both Unicode and byte strings
Aug 30 '08 #6
du**********@gmail.com wrote:
Hi,

How to check if something is a list or a dictionary or just a string?
Eg:

for item in self.__libVerDict.itervalues():
self.cbAnalysisLibVersion(END, item)
where __libVerDict is a dictionary that holds values as strings or
lists. So now, when I iterate this dictionary I want to check whether
the item is a list or just a string?
Thanks,
Rajat
Are you sure that is what you want to do or do you want to make sure that
"something" is an iterable. What if someone passed in a generator or a class
instance that is iterable, do you really want to fail?

-Larry
Aug 30 '08 #7

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

Similar topics

6
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that...
4
by: Mark Rae | last post by:
Hi, Is it possible to create a case-insensitive List<stringcollection? E.g. List<stringMyList = new List<string>; MyList.Add("MyString"); ...
7
by: Andrew Robinson | last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v> depending on input parameters and options to the method. 1. Is there any...
5
by: admin | last post by:
I have a class that has a function that should query a database and return a list of usernames as well as their id. What type should I use as a...
2
by: Assimalyst | last post by:
Hi I have a Dictionary<string, List<string>>, which i have successfully filled. My problem is I need to create a filter expression using all...
2
by: Terry Reedy | last post by:
SUBHABRATA, I recommend you study this excellent response carefully. castironpi wrote: It starts with a concrete test case -- an 'executable...
5
by: =?Utf-8?B?THVpZ2k=?= | last post by:
Hi all, having a List<stringand Dictionary<int, stringhow can I check that every string in the list is also in the Dictionary (and viceversa)?...
6
by: =?Utf-8?B?THVpZ2k=?= | last post by:
Hi all, I have to write a method that test a dictionary of this type: Dictionary<string, Dictionary<string, string>> to check if every string...
2
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I'm pulling records from or database by dates, and there are multiple records for each part number. The part numbers are being stored as strings...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

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.