Python split dictionary key at comma - python

I have a dictionary called muncounty- the keys are municipality, county. separted by a comma and the value is a zip code
muncounty['mun'+','+'county'] = 12345
My goal is to split the keys at the comma separating the mun and county and only extract the mun.
I have tried
muncounty.keys().split(',')
i know this does not work because you cannot use the split function on a list

You need some kind of looping, e.g. a list comprehension:
[key.split(',') for key in muncounty.keys()]

You're question and example code isn't very clear, but I think what you want is this:
for key in muncounty.keys():
mun, county = key.split(',')
Your current code is trying to perform split on a list, which you quite rightly point out can't be done. What the code above does is go through each key, and performs the split on it individually.

You could use map and a lambda function.
di = {'a.b':1}
map(lambda k: k.split('.'), di.keys())

[x.split(',')[0] for x in muncounty.keys()]
But I would recommend to store your key as tuple (municipality, county).

Well, verbose mode for that:
muncounty = {}
muncounty['mun'+','+'county'] = 12345
muncounty['mun2'+','+'county2'] = 54321
l = []
for i in muncounty:
l.append(i)
muns = []
for k in l:
muns.append(k.split(',')[0])
But dude... this is a really bad way to store mun/countries ;-)

Related

Given two list of words, than return as dictionary and set together

Hey (Sorry bad english) so am going to try and make my question more clear. if i have a function let's say create_username_dict(name_list, username_list). which takes in two list's 1 being the name_list with names of people than the other list being usernames that is made out of the names of people. what i want to do is take does two list than convert them to a dictonary and set them together.
like this:
>>> name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
>>> username_list = ["alejon", "carli", "hanri"]
>>> create_username_dict(name_list, username_list)
{
"Albert Jones": "alejon",
"Carlos Lion": "carli",
"Hanna Richardo": "hanri"
}
i have tried look around on how to connect two different list in too one dictonary, but can't seem to find the right solution
If both lists are in matching order, i.e. the i-th element of one list corresponds to the i-th element of the other, then you can use this
D = dict(zip(name_list, username_list))
Use zip to pair the list.
d = {key: value for key,value in zip(name_list, username_list)}
print(d)
Output:
{'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Considering both the list are same length and one to one mapping
name_list = ["Ola Nordmann", "Kari Olsen", "Roger Jensen"]
username_list = ["alejon", "carli", "hanri"]
result_stackoverflow = dict()
for index, name in enumerate(name_list):
result_stackoverflow[name] = username_list[index]
print(result_stackoverflow)
>>> {'Ola Nordmann': 'alejon', 'Kari Olsen': 'carli', 'Roger Jensen': 'hanri'}
Answer by #alex does the same but maybe too encapsulated for a beginner. So this is the verbose version.

Separate elements divided by comma in a list

I have a list of strings that contains elements of the type
List=['name1,vol', 'name1,price','name2, vol', 'name2,price'.... ]
I would like to extract a list only of "names" which are the parts that actually change as the second components in each element have a fix pattern (here:vol, price). Notice that the "names" can obviously have different length. To sum up, I'd like to extract something like:
List_names=['name1', 'name2' ]
How can I do that?
What if I have something of the type:
List_tricky=[('name1', 'vol'), ('name1', 'price'),('name2', 'vol'), ('name2', 'price').... ]
Something like this?
List=['name1,vol', 'name1,price','name2, vol', 'name2,price']
names = []
for string in List:
name = string.split(',')[0]
names.append(name)
print(names)
For your 'tricky' case, you can try:
# initialize variables:
names = []
# iterate over each point (tuple):
for point in List:
# get name:
name = point[0]
# append to list:
names.append(name)
print(names)
You could turn it into a dict then back into a list using str.split. (No loop required as it does it efficiently for you) Use functools.partial to apply the split to each string instead of a lambda:
from functools import partial
list(dict(map(partial(str.split, sep=','), List)))
This works for either input but way more simple for the list of tuples:
>>> l = ['name1,vol', 'name1,price','name2, vol', 'name2,price'.... ]
>>> list(dict(map(partial(str.split, sep=','), List)))
['name1', 'name2']
>>> l = [('name1', 'vol'), ('name1', 'price'),('name2', 'vol'), ('name2', 'price').... ]
>>> list(dict(l))
['name1', 'name2']
Similar logic to #Daniel Sokol's answer , you can use a one liner :
list2 = [x.split(',')[0] for x in List]
To add on top of #Alireza Tajadod's already wonderful answer, you might want to apply conversion to a set, then back to a list to remove any possible duplication items, as suggested by #Cryptoharf84 in the comments.
names_list = list(set([entry.split(',')[0] for entry in List]))
The same logic with list comprehension can be applied to the trickier case.
names_list_2 = list(set([entry[0] for entry in List_tricky]))
To make list comprehension more explicit, you can also do the following:
names_list_3 = list(set([name for name, _ in List_tricky]))
The _ indicates that we are discarding the second value of the unpacked tuple.
Sets are useful because converting a list with duplicate elements into a set effectively removes any duplications.
As a tip, look for naming conventions in python. But never name variables starting with upper case, nor with existing class names.
I will try something like:
list_names = [s.split(',')[0].strip() for s in List]
list_unique_names(set(list_names))
split returns a list of "chunks" of the original string, and strip to remove whitespaces on beginning/end of the resulting string.
I will change your data structure to dict instead of list
d={'name1': ('vol', 'price'),'name2': ('vol', 'price'), .... }
In order to get just the names:
d.keys()
You can also use a .map() function:
# Case 1: List
all_names = map(lambda x :a.split(',')[0], List)
# Case 2: List_tricky
all_names = [i[0] for i in List_tricky]
# After the code is the same
unique_names = set(all_names)
List_names = list(unique_names)
print(List_names)

Output a dictionary based on inputs from another dictionary and two lists

I have a dictionary and two lists and would like to output another dictionary that contains the individual list as the title and sum of the list contents as the values however, I have no clue as to how I could do this.
results = {'Apple':'14.0', 'Banana':'12.0', 'Orange':'2.0', 'Pineapple':'9.0'}
ListA = ['Apple','Pineapple']
ListB = ['Banana','Orange']
Output:
dicttotal = {'ListA':'23.0', 'ListB':'14.0'}
Edit: I have decided to use pandas to work with the above data as I find that the simplicity of pandas is more suited for my level of understanding. Thanks for the help everyone!
in python you can use list comprehensions to make this easy to read:
items_for_a = [float(v) for i, v in results.items() if i in ListA]
total_a = sum(items_for_a)
the dicttotal you want to print is strange, though. I don't think you want to print variable names as dictionary keys.
in python2 you should use .iteritems() instead of .items()
You can use fllowing code get ListA's sum. The same way for ListB. Just try it yourself
dicttotal = {}
ListASum = 0.0
ListBSum = 0.0
for item in ListA:
if item in results:
ListASum += float(results[item])
dicttotal['ListA'] = ListASum
Reduce and dictionary comprehension to create dictionary with an initial value, followed by updating a single value. Had key names not been variable names maybe could have done dict comprehension for both.
from functools import reduce
d_total = {'ListA': str(reduce(lambda x, y: float(results[x]) + float(results[y]), lista))}
d_total['ListB'] = str(reduce(lambda x, y: float(results[x]) + float(results[y]), listb))
{'ListA': '23.0', 'ListB': '14.0'}
Note: PEP-8 snake_case for naming
One-liner, using the (ugly) eval() function, but as Eduard said, it's better not to use variable names as keys :
{list_name: str(sum([float(results[item]) for item in eval(list_name)])) for list_name in ['ListA', 'ListB']}

Change dictionary values from int to string

This is what my dictionary looks like.
phoneBook = {"Skywalker": 55511243, "Solo": 55568711, "Vader": 55590858}
I need to change each phonenumber into a string and add "+1-" in front of it. But, I'm not sure how to do it.
With a simple dictionary comprehension:
r = {k: "+1-{}".format(v) for k,v in phoneBook.items()}
Where "+1-{}".format(v) converts to a string and prepends +1- to it. Similarly you could use "+1-" + str(v) as noted in the other answer but I personally find it less readable.
print(r)
{'Skywalker': '+1-55511243', 'Solo': '+1-55568711', 'Vader': '+1-55590858'}
Alternatively, if you want to do it in-place, i.e not create a new dictionary as comprehensions do, iterate over the keys* and update the values:
for k in phoneBook:
phoneBook[k] = "+1-{}".format(phoneBook[k])
*Iterating over the keys only is important, if you iterate over both keys and values you'll get odd behavior because you'll be altering the view you iterate through.
Use a dictionary comprehension
{k:'+1-'+str(phoneBook[k]) for k in phoneBook}

How can I sort this list in Python?

I have a list which contains a simple object of a class, say Person i.e:
my_list [Person<obj>, Person<obj> ..]
This Person object is very simple, has various variables, values i.e:
Person_n.name = 'Philip'
Person_n.height = '180'
Person_n.lives_in = 'apartment'
So as you can see, all these Persons live somewhere whether: apartment, house or boat.
What I want to create is a new list, or a dictionary (does not matter which) in which I have this list sorted in a way that they are grouped by their lives_in values and the most populated choice is the number one in the new list (or dictionary, in which lives_in value would be the key).
E.g.:
new_list = [('apartment', [Person_1, Person_5, Person_6, Person_4]), ('house': [Person_2, Peson_7]), ('boat': [Person_3])]
I am new to Python and I am stuck with endless loops. There must be a simple way to do this without looping through 4 times.
What is the Pythonic way to achieve this desired new list?
You need to sort it first before passing it to groupby:
sorted_list = sorted(my_list, key=lambda x: x.lives_in)
then use itertools.groupby:
from itertools import groupby
groupby(sorted_list, key=lambda x: x.lives_in)
result = [(key, list(group)) \
for key, group in groupby(sorted_list, key=lambda x: x.lives_in)]
people = my_list_of_people
people.sort(key=operator.attrgetter('lives_in')) # sort the people by where they live
groups = itertools.groupby(people, key=operator.attrgetter('lives_in')) # group the sorted people by where they live
Suppose your Person list is in myList and you want to create newList. I'm kind of new to stack overflow so I'm not using tabs. Can someone help me out lol. But here's the code:
for i in xrange(len(myList)):
found = false;
for j in xrange(len(newList)):
if newList[j][0]==myList[i].lives_in:
found = true;
newList[j][1].append(myList[i]);
if !found:
newList.append((myList[i].lives_in, [myList[i]]))

Categories

Resources