i'm trying to convert list of dictionaries to comma separated string , but some extra fields of dictionary are coming
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'}, {'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
expected output = TEST2,CUSTOMER/TEST 1
my script: s = [','.join(map(str,i.values())) for i in data]
output i'm getting : ['28,TEST 2,0,0', '27,CUSTOMER/TEST 1,0,0']
Try this:
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'}, {'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
print([d["name"] for d in data])
Output:
['TEST 2', 'CUSTOMER/TEST 1']
For the expected out, you simply need to get the value corresponding to the key name:
s = ','.join(i['name'] for i in data)
Data is defined as dictionary object. Apply elt for filter.
data = [{'groupid': '28', 'name': 'TEST 2', 'internal': '0', 'flags': '0'},
{'groupid':'27', 'name': 'CUSTOMER/TEST 1', 'internal': '0', 'flags': '0'}]
expected output = [elt["name"] for elt in data]
print(expected output)
output = ['TEST 2', 'CUSTOMER/TEST 1']
Related
I have a list inside a nested dictionary
body = {'Ready Date': '2020-01-31T12:00:00','Shipment Line List': [{'Description': 'Test', 'Weigth': '5',
'Height': '4.0','Length': '2.0', 'Width': '3.0'}, {'Description': 'Test', 'Weigth': '20', 'Height': '5',
'Length': '30', 'Width': '10']}
I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight"
I tried this approach, but I am not getting the expected output
key = {"Weigth":"Weight"}
def find_replace(dict_body, dictionary):
# is the item in the dict?
for item in dict_body:
# iterate by keys
if item in dictionary.keys():
# look up and replace
dict_body = dict_body.replace(item, dictionary[item])
# return updated dict
return dict_body
a = find_replace(body,key)
print(a)
I think a better idea in this particular case is to treat everything as a string, replace and back as a dictionary. Because if you have multiple nested keys, it might be just be easier this way in two lines of code:
from ast import literal_eval
body = literal_eval(str(body).replace("Weigth","Weight"))
This outputs:
{'Ready Date': '2020-01-31T12:00:00',
'Shipment Line List': [{'Description': 'Test',
'Height': '4.0',
'Length': '2.0',
'Weight': '5',
'Width': '3.0'},
{'Description': 'Test',
'Height': '5',
'Length': '30',
'Weight': '20',
'Width': '10'}]}
I want to iterate over the keys in the nested dictionary and replace "Weigth" with the correct spelling "Weight"
something like the below
body = {'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Weigth': '5',
'Height': '4.0', 'Length': '2.0', 'Width': '3.0'},
{'Description': 'Test', 'Weigth': '20',
'Height': '5',
'Length': '30', 'Width': '10'}]}
for entry in body['Shipment Line List']:
entry['Weight'] = entry['Weigth']
del entry['Weigth']
print(body)
output
{'Ready Date': '2020-01-31T12:00:00', 'Shipment Line List': [{'Description': 'Test', 'Height': '4.0', 'Length': '2.0', 'Width': '3.0', 'Weight': '5'}, {'Description': 'Test', 'Height': '5', 'Length': '30', 'Width': '10', 'Weight': '20'}]}
I'm trying to write some loops to retrieve values from the dictionary and print them as checkbuttons. Problem I'm having is that when I use the code as typed I get PY_VAR01, etc as my 'Names'
I know that i need to use .get() to get the value, but when I enter text=versions[2]['Name'].get() then my names appear as blank. I've been searching and trying different things and can't get anything to work so help would be appreciated or if someone could point me in the right direction.
versions = { 1: {'Name': '5.11 - CO', 'Location': '#',
'Name': 'WS 2016 V1607', 'Location': '#',
'Name': 'Win 10 PRO V1803', 'Location': '#',
'Name': 'TEST 1', 'Location': '#',
'Name': 'TEST 2', 'Location': '#',
'Name': 'Test 3', 'Location': '#',
'Name': 'TEST 4', 'Location': '#',
'Name': 'TEST 5', 'Location': '#',
},
2: {'Name':
# Version_5_5_EAC
v5_5_eac_options = Frame(optionsScreen)
v5_5_eac_options.grid()
for Name in versions:
versions[1]['Name'] = Variable()
l = Checkbutton(v5_5_eac_options, text=versions[1]['Name'], variable=versions[1]['Name'])
l.pack()
I would like the Checkbox to print the associated name (ie. 5.5 - (EAC)) insteady of PY_VAR01
SO thanks to everyone who helped. I mostly have it working now that I fixed the dictionary.
This is my updated code for the for loop but it's naming each checkbox with the same variable so I need to mess with it some more.
for Name in versions[1]:
var = Variable()
l = Checkbutton(v5_5_eac_options, text=versions[1][4]['Name'], variable=var)
l.pack()
You do not have to use get.
More, when an key, say Name is repeated in dictionary constructor, only one value is preserved.
versions = {1: {'Name': '5.5 - (EAC)', 'Location': '#',
'Name': 'WS 2012 RS', 'Location': '#',
'Name': 'Win 10 PRO V1607', 'Location': '#',
'Name': 'TEST 1', 'Location': '#',
'Name': 'TEST 2', 'Location': '#',
'Name': 'Test 3', 'Location': '#',
'Name': 'TEST 4', 'Location': '#',
'Name': 'TEST 5', 'Location': '#'}}
print (versions)
results in
{1: {'Name': 'TEST 5', 'Location': '#'}}
So you should first modify your data structure, e.g. nesting arrays like
versions = {1: [{'Name': '5.5 - (EAC)', 'Location': '#'},
{'Name': 'WS 2012 RS', 'Location': '#'},
...],
2:...
}
Now, to access say the fifth element of the list of Names, Test 2, we add index 4 (python lists start from 0)
text = version[1][4]['Name']
To render the last version only, something like
for record in versions[-1]:
record['variable'] = IntVar()
l = Checkbutton(v5_5_eac_options, text=record['Name'], variable=record['variable']
l.pack()
PS. I see question being updated to match the suggested answer
First, set up the dictionary as key: list of dictionary pairs:
versions = {
1: [
{'Name': '5.5 - (EAC)', 'Location': '#'},
{'Name': 'WS 2012 RS', 'Location': '#'},
{'Name': 'Win 10 PRO V1607', 'Location': '#'},
{'Name': 'TEST 1', 'Location': '#'},
{'Name': 'TEST 2', 'Location': '#'},
{'Name': 'Test 3', 'Location': '#'},
{'Name': 'TEST 4', 'Location': '#'},
{'Name': 'TEST 5', 'Location': '#'}
],
2: [
{'Name': '5.5 - S', 'Location': '#'},
{'Name': 'WS 2012 RS', 'Location': '#'},
{'Name': 'Win 10 PRO V1607', 'Location': '#'},
{'Name': 'TEST 1', 'Location': '#'},
{'Name': 'TEST 2', 'Location': '#'},
{'Name': 'Test 3', 'Location': '#'},
{'Name': 'TEST 4', 'Location': '#'},
{'Name': 'TEST 5', 'Location': '#'}
]
}
Then, you can access each Name using a nested for loop:
for index, version in in versions.items():
for record in version:
print(record['Name'])
Since I'm not sure what you're doing with each index or record in this dictionary, you'll need to map it to a checkbox however you're using those in your application.
EDIT:
You want to have two separate for loops based on your edit.
for record in versions[1]:
print record['Name']
and
for record in versions[2]:
print record['Name']
I have a list of dictionaries. Some dictionaries share the same elements.
data = [
{'New_PCP_Name': 'Jack0',
'Member_Name': 'Jack0, 0',
'Member_ID': '111',
'DOB': '111',
'PCP_ID':'111'
},
{'New_PCP_Name': 'Jack0',
'Member_Name': 'Jack00, 00',
'Member_ID': '222',
'DOB': '222',
'PCP_ID':'111'
},
{'New_PCP_Name': 'Jack1',
'Member_Name': 'Jack1, 1',
'Member_ID': '333',
'DOB': '333',
'PCP_ID':'333'
},
{'New_PCP_Name': 'Jack2',
'Member_Name': 'Jack2, 2',
'Member_ID': '444',
'DOB': '444',
'PCP_ID':'444'
}
]
I need to combine them in a specific format. The first 2 dicts share the same element 'New_PCP_Name': 'Jack0'. So I want to combine them. The final product is as below. This format has to be exactly like this because I need to use this format in a mail merge from the data imported from Excel.
data = [
{'New_PCP_Name': 'Jack0',
'PCP_ID':'111',
'Member_Name':[{'Member_Name':'Jack0, 0','Member_ID':'111','DOB':'111'},
{'Member_Name': 'Jack00, 00', 'Member_ID': '222', 'DOB': '222'}]
},
{'New_PCP_Name': 'Jack1',
'Member_Name': 'Jack1, 1',
'Member_ID': '333',
'DOB': '333',
'PCP_ID':'333'
},
{'New_PCP_Name': 'Jack2',
'Member_Name': 'Jack2, 2',
'Member_ID': '444',
'DOB': '444',
'PCP_ID':'444'
}
]
I'm new in python.I have tried breaking up the list, modifying the dictionaries and putting them back together as below. That didn't work out. Please help me figure out how to reformat the list of dicts. Or is there a way to import data from Excel in that specific format for the rows that share the same cell values?
data2=[]
for x in range (0,len(data),1):
print(x)
print(data[x])
a = data[x]
print(a['New_PCP_Name'])
if x+1<=len(data):
if data[x]['New_PCP_Name'] == data[x+1]['New_PCP_Name']:
print('yes')
data2.append(data[x])
else:
print('no')
print('data2=', data2)
One possibility is using itertools.groupby (doc):
data = [
{'New_PCP_Name': 'Jack0',
'Member_Name': 'Jack0, 0',
'Member_ID': '111',
'DOB': '111',
'PCP_ID':'111'
},
{'New_PCP_Name': 'Jack0',
'Member_Name': 'Jack00, 00',
'Member_ID': '222',
'DOB': '222',
'PCP_ID':'111'
},
{'New_PCP_Name': 'Jack1',
'Member_Name': 'Jack1, 1',
'Member_ID': '333',
'DOB': '333',
'PCP_ID':'333'
},
{'New_PCP_Name': 'Jack2',
'Member_Name': 'Jack2, 2',
'Member_ID': '444',
'DOB': '444',
'PCP_ID':'444'
}
]
from itertools import groupby
out = []
for v, g in groupby(sorted(data, key=lambda k: k['New_PCP_Name']), lambda k: (k['New_PCP_Name'], k['PCP_ID'])):
l = [*g]
if len(l) == 1:
out.append(l[0])
else:
pcp_id = None
for i in l:
del i['New_PCP_Name']
del i['PCP_ID']
out.append({'New_PCP_Name': v[0],
'PCP_ID': v[1],
'Member_Name':l
})
from pprint import pprint
pprint(out)
Prints:
[{'Member_Name': [{'DOB': '111', 'Member_ID': '111', 'Member_Name': 'Jack0, 0'},
{'DOB': '222',
'Member_ID': '222',
'Member_Name': 'Jack00, 00'}],
'New_PCP_Name': 'Jack0',
'PCP_ID': '111'},
{'DOB': '333',
'Member_ID': '333',
'Member_Name': 'Jack1, 1',
'New_PCP_Name': 'Jack1',
'PCP_ID': '333'},
{'DOB': '444',
'Member_ID': '444',
'Member_Name': 'Jack2, 2',
'New_PCP_Name': 'Jack2',
'PCP_ID': '444'}]
Try
new_data_dic = {}
for e in data:
new_name = e['New_PCP_Name']
if new_name not in new_data_dic:
new_data_dic[new_name] = e.copy()
else:
if type(new_data_dic[new_name]['Member_Name'] == str):
inner = new_data_dic[new_name].copy()
del inner['New_PCP_Name']
del new_data_dic[new_name]['Member_ID']
del new_data_dic[new_name]['DOB']
new_data_dic[new_name]['Member_Name'] = [inner]
inner = e.copy()
del inner['New_PCP_Name']
new_data_dic[new_name]['Member_Name'].append(inner)
data2 = list(new_data_dic.values())
Explained: The 'New_PCP_Name' is a key, so I create a dictionary. I transform 'Member_Name' to a list in case I see another occurence of the same key. On subsequent appearances I can append.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How do I get the value of an item in the list when requesting its "key"?
e.g. I currently have the following list:
[{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
How do I cycle through to print the title and revision of each file
Dictionary = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, ...
KeyList = ['rev', 'time', 'action', 'type', 'title']
for Key in KeyList:
print Key, "=", Dictionary[title]
And I am currently getting the following error:
Traceback (most recent call last):
File "P:/Scripts/PerforceSearchTool.py", line 45, in <module>
GetFiles()
File "P:/Scripts/PerforceSearchTool.py", line 28, in GetFiles
print Key, "=", Dictionary[depotFile]
NameError: global name 'depotFile' is not defined
The list in the end will contain thousands of files. I would like to be able to search the list for each of the files titles. And for the matching title return its title, depending on its action.
You can use a for loop:
mylist = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'}, {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for i in mylist:
print("Title: {}, Revision: {}".format(i["title"],i["rev"]))
Output:
Title: test.log, Revision: 1
Title: python.py, Revision: 0
Title: Hello.txt, Revision: 12
To print title and revision of each element you can do something like this:
a = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'}, {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for e in a:
print e['title'] + ' ' + e['rev']
It outputs this data:
test.log 1
python.py 0
Hello.txt 12
try this:
a = [{'rev': '1', 'time': '1448300582', 'action': 'move/add', 'title': 'test.log'}, {'rev': '0', 'time': '1448300582', 'action': 'delete', 'title': 'python.py'} {'rev': '12', 'time': '1448300582', 'action': 'move/add', 'title': 'Hello.txt'}]
for x in range(len(a)):
print a[x]['title']
print a[x]['rev']
Greetings
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
In my python code , I get strings from the text file like :
a = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.single.com'}]}]"
b ="[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]}]"
c ="[{'index': '1', 'selected': 'true', 'length': '103674793', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/002.mp3', 'uris': []}, {'index': '2', 'selected': 'true', 'length': '62043128', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/004.mp3', 'uris': []}, {'index': '3', 'selected': 'true', 'length': '57914945', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/003.mp3', 'uris': []}]"
I want to get the text of the value uris , the output should looks like :
a = [{'status': 'used', 'uri': 'http://www.single.com'}]
b = [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]
c = [[],[],[]]
Many hours I spent in failed trials to get this result by using the string functions ,
uris = str.split('}, {')
for uri in uris :
uri = uri.split(',')
# and so on ...
but , it work so bad especially in the second case , I hope that anyone can do it by regex or any other way.
They are all python literals. You can use ast.literal_eval. No need to use regular expression.
>>> a = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.single.com'}]}]"
>>> b = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]}]"
>>> c = "[{'index': '1', 'selected': 'true', 'length': '103674793', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/002.mp3', 'uris': []}, {'index': '2', 'selected': 'true', 'length': '62043128', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/004.mp3', 'uris': []}, {'index': '3', 'selected': 'true', 'length': '57914945', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/003.mp3', 'uris': []}]"
>>> import ast
>>> [x['uris'] for x in ast.literal_eval(a)]
[[{'status': 'used', 'uri': 'http://www.single.com'}]]
>>> [x['uris'] for x in ast.literal_eval(b)]
[[{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]]
>>> [x['uris'] for x in ast.literal_eval(c)]
[[], [], []]
in javascript you can do this
a = a.replace(/^.*uris[^[]*(\[[^\]]*\]).*$/, '\1');
if php would be this a way
$a = preg_replace('/^.*uris[^[]*(\[[^\]]*\]).*$/', '\1', $a);
edit: well I see, it wouldn't do your complete task for 'c' -.-