I have a list of personal data(id_code,birth_year,born_in) and i want to sort the any arrays in list but i have a problem in this work.
my list data :
data = [
'id_code:3211238576;birth_year:1350;born_in:Boushehr',
'id_code:9801233575;born_in:Argentina;birth_year:1360',
'born_in:Portugal;id_code:0219206431;birth_year:1358',
'id_code:0021678913;born_in:Shiraz;birth_year:1120',
'id_code:1101102135;born_in:Gilan;birth_year:1152',
]
The code I wrote and has an bug:
for i in data:
s = ''.join(sorted(i))
print(s)
my code output:
01112233355678:::;;B___abbcddeeehhhiiinnooorrrrstuy
00112333556789:::;;A___aabbcddeeeghiiiinnnnoorrrrtty
00111223345689:::;;P___aabbcddeeghiiilnnooorrrrttuy
00011112236789:::;;S___aabbcddeehhiiiinnoorrrrtyz
00111111122355:::;;G___aabbcddeehiiiilnnnoorrrty
But! The code to i want to have in output(True answer):
id_code:3211238576,born_in:Boushehr,birth_year:1350
id_code:9801233575,born_in:Argentina,birth_year:1360
id_code:0219206431,born_in:Portugal,birth_year:1358
id_code:0021678913,born_in:Shiraz,birth_year:1120
id_code:1101102135,born_in:Gilan,birth_year:1152
Please help me to solve this problem
Assuming you want your fields to be in specific order, try this one: (I put comments in code for clarification):
data = [
'id_code:3211238576;birth_year:1350;born_in:Boushehr',
'id_code:9801233575;born_in:Argentina;birth_year:1360',
'born_in:Portugal;id_code:0219206431;birth_year:1358',
'id_code:0021678913;born_in:Shiraz;birth_year:1120',
'id_code:1101102135;born_in:Gilan;birth_year:1152',
]
def sorter(x: str):
# getting the field name
field = x.split(':')[0]
# returning it's index from "sorted_by" list
return sorted_by.index(field)
# The index of these fields will be used for sorting in "sorter" function.
sorted_by = ['id_code', 'born_in', 'birth_year']
result = []
for item in data:
# splitting the fields
splited = item.split(';')
splited.sort(key=sorter)
# building the line back and append it
result.append(';'.join(splited))
for i in result:
print(i)
output :
id_code:3211238576;born_in:Boushehr;birth_year:1350
id_code:9801233575;born_in:Argentina;birth_year:1360
id_code:0219206431;born_in:Portugal;birth_year:1358
id_code:0021678913;born_in:Shiraz;birth_year:1120
id_code:1101102135;born_in:Gilan;birth_year:1152
Now you can easily change the fields order in sorted_by list and see the result.
Try
out = [';'.join(reversed(sorted(x.split(';')))) for x in data]
print(out)
This takes every element of the data list and splits it in three strings, each of which contains one of the three attributes. Then, it arranges the three strings in reversed alphabetical order and joins them back into one string, separated by ';'
Related
I'm trying to make a function that takes in list of strings as an input like the one listed below:
def swap_values_dict(['Summons: Bahamut, Shiva, Chocomog',
'Enemies: Bahamut, Shiva, Cactaur'])
and creates a dictionary from them using the words after the colons as keys and the words before the colons as values. I need to clarify that, at this point, there are only two strings in the list. I plan to split the strings into sublists and, from there, try and assign them to a dictionary.
The output should look like
{'Bahamut': ['Summons','Enemies'],'Shiva':['Summons','Enemies'],'Chocomog':['Summons'],'Cactaur':['Enemies']}
As you can see, the words after the colon in the original list have become keys while the words before the colon (categories) have become the values. If one of the values appears in both lists, it is assigned two values in the final dictionary. I would like to be able to make similar dictionaries out of many lists of different sizes, not just ones that contain two strings. Could this be done without list comprehension and only for loops and if statements?
What I've Tried So Far
title_list = []
for i in range(len(mobs)):#counts amount of strings in list
titles = (mobs[i].split(":"))[0] #gets titles from list using split
title_list.append(titles)
title_list
this code returns ['Summons', 'Enemies'] which aren't the results I wanted to receive but I think they could help me write the function. I had planned on separating the keys and values into separate lists and then zipping them together afterwards as a dictionary.
Try:
def swap_values_dict(lst):
tmp = {}
for s in lst:
k, v = map(str.strip, s.split(":"))
tmp[k] = list(map(str.strip, v.split(",")))
out = {}
for k, v in tmp.items():
for i in v:
out.setdefault(i, []).append(k)
return out
print(
swap_values_dict(
[
"Summons: Bahamut, Shiva, Chocomog",
"Enemies: Bahamut, Shiva, Cactaur",
]
)
)
Prints:
{
"Bahamut": ["Summons", "Enemies"],
"Shiva": ["Summons", "Enemies"],
"Chocomog": ["Summons"],
"Cactaur": ["Enemies"],
}
I'd use a defaultdict. It saves you the trouble of manually checking if a key exists in your dictionary and constructing a new empty list, making for a rather concise function:
from collections import defaultdict
def swap_values_dict(mobs):
result = defaultdict(list)
for elem in mobs:
role, members = elem.split(': ')
for m in members.split(', '):
result[m].append(role)
return result
New to python and for this example list
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
There are 3 categories of name, job, and gender. I would want those 3 categories to be on the same line which would look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
My actual list is really big with 10 categories I would want to be on the same line. I am also trying to figure out a way where if one of the categories is not in the list, it would print something like N/A to indicate that it is not in the list
for example I would want it to look like
<name>bob</name>, <job>doctor</job>, <gender>male</gender>
<name>susan</name>, <job>teacher</job>, <gender>female</gender>
<name>john</name>, N/A, <gender>male</gender>
What would be the best way to do this?
This is one way to do it. This would handle any length list, and guarantee grouping no matter how long the lists are as long as they are in the correct order.
Updated to convert to dict, so you can test for key existence.
lst = ['<name>bob</name>', '<job>doctor</job>', '<gender>male</gender>', '<name>susan</name>', '<job>teacher</job>', '<gender>female</gender>', '<name>john</name>', '<gender>male</gender>']
newlst = []
tmplist = {}
for item in lst:
value = item.split('>')[1].split('<')[0]
key = item.split('<')[1].split('>')[0]
if '<name>' in item:
if tmplist:
newlst.append(tmplist)
tmplist = {}
tmplist[key] = value
#handle the remaining items left over in the list
if tmplist:
newlst.append(tmplist)
print(newlst)
#test for existance
for each in newlst:
print(each.get('job', 'N/A'))
I have two values number and sys_id. I have made seperate list for both of the values. How can save it in any other data structure like dictionary, or something else because i those list of number and sys_id are related. I am doing it in Python
Below Is the code what i have done
ticket_num.append(resp['result'][idx]['number'])
sys_id.append(resp['result'][idx]['sys_id']) ```
This is making two list one for ticket_num and sys_id. As Ticket number and sys_id are related for example ticket_num = ['INC00012','INC00013','INC00014' ] ,
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
As this list are related like ticket_num[0] is directly link with sys_id[0]
So can i make a dictionary that contains ticket_num, sys_id directly without creating lists(for e.g. : {ticket_num : '...' , sys_id = '....' , ..... }
Use zip with dict
Ex:
ticket_num = ['INC00012','INC00013','INC00014' ]
sys_id = ['644323432sfasesdf213', '644323432dfgdfkdskrwwr', 'f283044423fdldsf09']
print(dict(zip(ticket_num, sys_id)))
Output:
{'INC00012': '644323432sfasesdf213',
'INC00013': '644323432dfgdfkdskrwwr',
'INC00014': 'f283044423fdldsf09'}
Welcome to Stackoverflow.
Do you actually need the lists of ticket numbers and IDs? If not that you could instead consider building the structure you need instead of the lists.
You don't say whether you want to be able to look up IDs from ticket numbers or vice versa. This solution allows you to do either:
idx_from_ticket = {}
ticket_from_idx = {}
# In the loop that produces the values, instead of the current appends ...
temp = resp['result'][idx]
idx = temp['sys_id]
number = temp['number']
idx_from_ticket[number] = idx
ticket_from_idx[idx] = number
The two dictionaries can then be used to correlate the IDs and ticket numbers. If you want to actually do something else then I hope this code gives you enough clues.
If you do already have the lists and want to retain them then the zip function is your friend.
idx_from_ticket = dict(zip(ticket_num, sys_id))
ticket_from_idx = dict(zip(sys_id, ticket_num))
zip, when called with two argument, yields a sequence of two-element tuples, which the
dict function assumes are key/value pairs.
I've run into the following issue, with my code below. Basically I have a list of objects with an id and a corresponding weight, and I have another list of id's. I want to use only the weights of the objects matching the id's in the second list.
d_weights = [{'d_id':'foo', 'weight': -0.7427}, ...]
d_ids = ['foo', ...]
for dtc_id in d_ids:
d_weight = next((d['weight'] for d in d_weights if d['d_id'] == dtc_id), "")
print str(d_weight)
if str(d_weight) != "":
print "not empty string! "+str(d_weight)
The output for this is:
-0.7427
0.0789
-0.0039
-0.2436
-0.0417
not empty string! -0.0417
Why is only the last one not empty when I can print them fine and they are obviously not equal to an empty string? How do I check that the next() actually returned something before using it?
You haven't correct algorithm.
So d_weight = next((d['weight'] for d in d_weights if d['d_id'] == dtc_id), "") iterate only once.
On every cycle for weight_dict in d_weights: you've got only first dict of d_weights.
Without more data, i can't reproduce your output.
In my case it works fine:
-0.7427
not empty string! -0.7427
-0.327
not empty string! -0.327
Correct code you can find in DhiaTN's answer.
just iterate of the list of the keys and get the values from each dict :
for weight_dict in d_weights
for key in d_ids:
print weight_dict.get(key, "")
I am trying to learn how to manipulate data in python.
I have the following data in a txt file
{"summonerId":000000,"games":[{"gameId":111111,"invalid":false,"gameMode":"CLASSIC","gameType":"MATCHED_GAME","subType":"NORMAL","mapId":11,"teamId":200,"championId":89,"spell1":3,"spell2":4,"level":30,"ipEarned":237,"createDate":1443314494341,"fellowPlayers":[{"summonerId":46350758,"teamId":100,"championId":157}],"stats":{"level":15,"goldEarned":10173,"numDeaths":5,"minionsKilled":48,"championsKilled":1,"goldSpent":9205,"totalDamageDealt":48752,"totalDamageTaken":23464,"team":200,"win":true,"largestMultiKill":1,"physicalDamageDealtPlayer":9064,"magicDamageDealtPlayer":35714,"physicalDamageTaken":18944,"magicDamageTaken":4005,"timePlayed":1831,"totalHeal":4129,"totalUnitsHealed":5,"assists":24,"item0":3401,"item1":2049,"item2":3117,"item3":3068,"item4":3075,"item5":1028,"item6":3340,"magicDamageDealtToChampions":9062,"physicalDamageDealtToChampions":3348,"totalDamageDealtToChampions":12411,"trueDamageDealtPlayer":3974,"trueDamageTaken":514,"wardKilled":1,"wardPlaced":16,"totalTimeCrowdControlDealt":104,"playerRole":2,"playerPosition":4}]}
My end goal is to be able to display a specific piece of information from the "stats" dictionary.
When I run the following code
import json
matches = open('testdata.txt', 'r')
output = matches.read()
data=json.loads(output)
display = data["games"]
print("Info: " + str(display))
The output is everything that corresponds to the "games" key as I would expect.
When I try
import json
matches = open('testdata.txt', 'r')
output = matches.read()
data=json.loads(output)
display = data["games"]["stats"]
print("Info: " + str(display))
I receive: TypeError: list indices must be integers, not str
I'm not really sure how to proceed given that the key is clearly a string and not an integer...
Your data["games"] value is a list; each element in that list is a dictionary, and it is those dictionaries in the list that (may) have the 'stats' key. A list can contain 0 or more elements; in this specific case there is just 1 but there could be more or none.
Loop over the list of dictionaries, or pick a specific dictionary from the list with indexing. Since there is only one in your specific example, you could just index that 1 element with the 0 index:
display = data["games"][0]["stats"]