3 votes

ajouter deux dictionnaires qui sont déjà dans la même liste

J'ai une colonne de 50983 lignes. chaque ligne a une liste à l'intérieur de laquelle il y a deux dictionnaires ou plus. je veux faire tous les dictionnaires dans un seul dictionnaire. je veux mettre à jour cet id dans chaque dictionnaire. j'ai utilisé :

l=[{'id':'abc12vr'},{'createdAt': '2018-12-18T16:09:57.098Z',
  'notes': 'Candidate initial submission.',
  'createdBy': 'Steven Klinger'},
 {'createdAt': '2018-12-18T23:14:09.415Z',
  'notes': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2019-01-22T16:04:46.958Z',
  'notes': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2018-12-18T16:09:57.098Z',
  'notes': 'Candidate initial submission.',
  'createdBy': 'Steven Klinger'},
 {'createdAt': '2018-12-18T23:14:09.415Z',
  'notes': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2019-01-22T16:04:46.958Z',
  'notes': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>',
  'createdBy': 'Matt'}]

id_dict = [d for d in l if 'id' in d][0]
merge = [{**d,**id_dict} for d in l if 'id' not in d]

Mais je n'obtiens que la dernière rangée avec un seul dictionnaire, je voulais que chaque rangée

1voto

Pushpa Rathod Points 11

C'est ma première réponse dans stackflow et j'espère qu'elle pourra vous aider !

Vous n'obtenez que la dernière ligne avec un seul dictionnaire, je voulais chaque ligne - parce que le dictionnaire doit avoir une clé unique et comme toutes les clés dans les dictionnaires sont les mêmes, c'est là que python continue à écraser les clés.

Le code ci-dessous fusionne tous les dictionnaires en un seul et ajoute une valeur de compteur aux clés pour les rendre uniques.

merged_dict={}
counter=0
def merge_logic(dict_para):
    #print dict_val
    global counter
    for key,value in dict_para.items():    
        merged_dict[key+"_"+str(counter)]=value
        counter+=1
id_dict = [merge_logic(d) for d in l if isinstance(d,dict)]

print merged_dict

Sortie :

    {'createdAt_11': '2018-12-18T16:09:57.098Z', 
'notes_0': 'Candidate initial submission.', 
'notes_3': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 
'createdAt_14': '2018-12-18T23:14:09.415Z', 
'createdAt_17': '2019-01-22T16:04:46.958Z', 
'notes_6': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>', 
'notes_9': 'Candidate initial submission.', 
'createdBy_13': 'Matt', 
'notes_12': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 
'createdAt_5': '2018-12-18T23:14:09.415Z', 
'notes_15': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>', 
'createdAt_2': '2018-12-18T16:09:57.098Z', 
'createdBy_4': 'Matt', 
'createdBy_7': 'Matt', 
'createdBy_1': 'Steven Klinger', 
'createdAt_8': '2019-01-22T16:04:46.958Z', 
'createdBy_10': 'Steven Klinger', 
'createdBy_16': 'Matt'}

J'espère que cela vous aidera !

0voto

On dirait que ce devrait vous aider (mais je n'en suis pas sûr puisque vous n'avez pas fourni la sortie souhaitée) :

d = {}
for i in l:
    for k in i.keys():
        d[k] = list(d[k] for d in l)

{'createdAt': ['2018-12-18T16:09:57.098Z', '2018-12-18T23:14:09.415Z', '2019-01-22T16:04:46.958Z', '2018-12-18T16:09:57.098Z', '2018-12-18T23:14:09.415Z', '2019-01-22T16:04:46.958Z'], 'notes': ['Candidate initial submission.', 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>', 'Candidate initial submission.', 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>'], 'createdBy': ['Steven Klinger', 'Matt', 'Matt', 'Steven Klinger', 'Matt', 'Matt']}

0voto

Brian Joseph Points 1375

Cela fait un passage sur les données :

from collections import defaultdict

output_dict = defaultdict(list)

for d in l:
    for key in d:
        output_dict[key].append(d[key])

>>> output

defaultdict(list,
            {'createdAt': ['2018-12-18T16:09:57.098Z',
              '2018-12-18T23:14:09.415Z',
              '2019-01-22T16:04:46.958Z',
              '2018-12-18T16:09:57.098Z',
              '2018-12-18T23:14:09.415Z',
              '2019-01-22T16:04:46.958Z'],
             'notes': ['Candidate initial submission.',
              'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
              'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>',
              'Candidate initial submission.',
              'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
              'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>'],
             'createdBy': ['Steven Klinger',
              'Matt',
              'Matt',
              'Steven Klinger',
              'Matt',
              'Matt']})

0voto

Akash Swain Points 514

Réponse originale

J'ai supposé que vous aviez besoin d'une clé et de toutes les valeurs de cette clé à ajouter dans une liste. Ici, j'ai utilisé setdefault méthode de dictionary pour y parvenir.

# Input
l=[{'createdAt': '2018-12-18T16:09:57.098Z',
  'notes': 'Candidate initial submission.',
  'createdBy': 'Steven Klinger'},
 {'createdAt': '2018-12-18T23:14:09.415Z',
  'notes': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2019-01-22T16:04:46.958Z',
  'notes': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2018-12-18T16:09:57.098Z',
  'notes': 'Candidate initial submission.',
  'createdBy': 'Steven Klinger'},
 {'createdAt': '2018-12-18T23:14:09.415Z',
  'notes': 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>',
  'createdBy': 'Matt'},
 {'createdAt': '2019-01-22T16:04:46.958Z',
  'notes': 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>',
  'createdBy': 'Matt'}]

# Main code
res = {} # defined output dict
for i in l: # for loop to fetch each element(dict) inside a list
    for k, v in i.items(): # to fetch key value fair of each dict
        res.setdefault(k, []).append(v) # setdefault method of add key to result and created an empty list and appended value to it.  
print (res) # print result

# Output
# {'createdAt': ['2018-12-18T16:09:57.098Z', '2018-12-18T23:14:09.415Z', '2019-01-22T16:04:46.958Z', '2018-12-18T16:09:57.098Z', '2018-12-18T23:14:09.415Z', '2019-01-22T16:04:46.958Z'], 'notes': ['Candidate initial submission.', 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>', 'Candidate initial submission.', 'The Candidate Status has now been updated from <strong>CV Submitted</strong> and <strong>Feedback Pending</strong> to <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong>', 'The Candidate Status has now been updated from <strong>Client CV Review</strong> and <strong>Feedback Awaiting</strong> to <strong>Client CV Review</strong> and <strong>Position on Hold</strong>'], 'createdBy': ['Steven Klinger', 'Matt', 'Matt', 'Steven Klinger', 'Matt', 'Matt']}

Réponse modifiée

# NOTE: "l" is individual list of the your data set.
value_for_id = "abc" # Value to be set for id
for i in l: # For each element in l - where l is your individual list
    if i.get("id",None) is not None: # verify if dict with key -> "id" exist
        i["id"] = value_for_id # If exist then update the value for key -> "id"
        break # break and come out of the for loop
else: # if there is no break, i.e. data doesn't have dict with "id" then we will append a new dict to the list. 
    l.append({"id":value_for_id}) # Appending new dict to the list

print (l)

J'espère que cela vous aidera et comptera !

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X