Seite 1 von 1
					
				Wie kann ich nested list/dict ermitteln?
				Verfasst: Mittwoch 7. April 2010, 15:38
				von maxwell
				Hallo @all,
ich stehe total auf dem Schlauch. Wie die headline schon sagt, wie
kann ich auf einer Ebene erkennen ob der value eine nested 
liste/dict handelt.
Viele Grüße,
Chris
EDIT: Bitte verschieben, habe zuerst die Suche gequält und wohl im falschen Forum geposted...
Edit (BlackJack): Nach "Allgemeine Fragen" verschoben. 
			
					
				
				Verfasst: Mittwoch 7. April 2010, 15:53
				von DasIch
				Kommt auf den Kontext an. Welche Datenstrukturen möchtest du den akzeptieren und wofür? Eventuell macht es Sinn einen Algorithmus hinter mehreren Funktionen zu verstecken die unterschiedliche Parameter entgegen nehmen.
			 
			
					
				
				Verfasst: Mittwoch 7. April 2010, 16:33
				von maxwell
				hallo, 
der kontext ist der, dass daraus ein dict. erzeugt werden soll. 
akzeptiert werden soll als key, val kombi. ein tuple order liste oder 
ein reines dict.
Code: Alles auswählen
a=[['k1','v1'],['k2','v2'], ('k3','v3')]
# oder
a=[{'k1':'v1'}]
Sobald der value ein mutable (liste/dict) ist soll ein fehler geworfen werden.
Code: Alles auswählen
error=[['k1', ['kx','vx']], ('k2', {'kx':'vx'}), ('k3', ['kx','kx'])]
# oder
error=[{'k1': {'kx':'vx'}}]
gr. chris
 
			
					
				
				Verfasst: Mittwoch 7. April 2010, 16:48
				von derdon
				Code: Alles auswählen
>>> def check_dict(d):
...     for k,v in d.iteritems():
...         if isinstance(v, (list, dict)):
...             raise TypeError("value {0!r} of the dict {1!r} must not be of the type 'list' or 'dict'".format(v, d))
... 
>>> a = [['k1','v1'],['k2','v2'], ('k3','v3')]
>>> check_dict(dict(a))
>>> error = [['k1', ['kx','vx']], ('k2', {'kx':'vx'}), ('k3', ['kx','kx'])]
>>> check_dict(dict(error))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 4, in check_dict
TypeError: value ['kx', 'kx'] of the dict {'k3': ['kx', 'kx'], 'k2': {'kx': 'vx'}, 'k1': ['kx', 'vx']} must not be of the type 'list' or 'dict'
(benötigt Python2.x)
 
			
					
				
				Verfasst: Mittwoch 7. April 2010, 17:44
				von maxwell
				Thanks! 
ähnliches habe ich bereits nur wusste ich nicht wie mit der liste umgehen wg. Iteritems.
			 
			
					
				
				Verfasst: Mittwoch 7. April 2010, 18:34
				von jbs
				Was hast du eigentlich vor? Also warum brauchst du das?