[Tutor] update list of dictionaries based on key
ski
norman at khine.net
Fri Mar 13 16:09:58 CET 2009
Hello,
Here is what I have so far:
>>> mylist = [{'index': 0, 'title': 'Association of British Travel
Agents', 'selected': False, 'edit_row': '?edit_affiliation=0',
'affiliation': 'ABTA', 'affiliation_no': u'G3903'}, {'index': 1,
'title': 'Appointed Agents of IATA', 'selected': False, 'edit_row':
'?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no':
u'none'}, {'index': 0, 'title': 'Association of Airline Cons.',
'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation':
'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': 'Association of
British Travel Agents', 'selected': False, 'edit_row':
'?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no': u'zser'}]
>>> key = 'affiliation_no'
>>> my_dup_keys = []
>>> merged_list = []
>>> mykeys = [item['affiliation'] for item in mylist]
>>> for x in mykeys:
if mykeys.count(x) >= 2:
my_dup_keys.append(x)
>>> for item in mylist:
if item['affiliation'] in set(my_dup_keys):
merged_list.append(item)
>>> values = [d[key] for d in merged_list if d.has_key(key)]
>>> for dict in merged_list:
dict[key] = values
mylist.append(dict)
>>> print mylist
[{'index': 0, 'title': 'Association of British Travel Agents',
'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation':
'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title':
'Appointed Agents of IATA', 'selected': False, 'edit_row':
'?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no':
u'none'}, {'index': 0, 'title': 'Association of Airline Cons.',
'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation':
'AAC', 'affiliation_no': u'sss'}, {'index': 1, 'title': 'Association of
British Travel Agents', 'selected': False, 'edit_row':
'?edit_affiliation=1', 'affiliation': 'ABTA', 'affiliation_no':
[u'G3903', u'zser']}, {'index': 0, 'title': 'Association of British
Travel Agents', 'selected': False, 'edit_row': '?edit_affiliation=0',
'affiliation': 'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index':
1, 'title': 'Association of British Travel Agents', 'selected': False,
'edit_row': '?edit_affiliation=1', 'affiliation': 'ABTA',
'affiliation_no': [u'G3903', u'zser']}]
This sort of works but I want to return a list that updates 'mylist' not
append to it, so I will get:
[{'index': 0, 'title': 'Association of British Travel Agents',
'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation':
'ABTA', 'affiliation_no': [u'G3903', u'zser']}, {'index': 1, 'title':
'Appointed Agents of IATA', 'selected': False, 'edit_row':
'?edit_affiliation=1', 'affiliation': 'IATA', 'affiliation_no':
u'none'}, {'index': 0, 'title': 'Association of Airline Cons.',
'selected': False, 'edit_row': '?edit_affiliation=0', 'affiliation':
'AAC', 'affiliation_no': u'sss'}]
Thanks
Norman
More information about the Tutor
mailing list