I have a array of hashes like:
detail = [{'name': 'Adam'}, {'name': 'Jackie'}]
Now what I want to do is create a new dict like:
{'name' : 'Sandra'}
What I did was:
for i in detail:
for key_in_i in i:
dict(key_in_i = 'Sandra')
What I would like to get is {'Name': 'Sandra'}
. But if I do this I am getting {'key_in_u': 'Sandra'}
because I have set the key as key_in_i
. I don't know how to access the value of key from for loop to the new dict. If it was in Ruby I would have done #{key_in_i}
and it would have given me the required value. I also tried new_dict = dict("%s" %key = i[key])
but it gives me error key cannot be the expression
. I would be thankful if anyone could help me solve this issue!
The easiest solution in this particular case is
for i in detail:
print dict.fromkeys(i, "Sandra")
You could also use a dictionary literal:
for i in detail:
for key_in_i in i:
{key_in_i: "Sandra"}
(Not sure what you are actually trying to achieve since your example code is effectively doing nothing.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.