Nested Dictionary from Lists and Other Dictionaries - python-2.7

I am trying to make a master dictionary from preexisting lists and dictionaries. I am having a hard time getting it to work like I think it should.
I have a list of student names.
names=[Alice, Bob, Charles, Dan]
I then have 2 dictionaries that have info based on student ID number and another piece of info.
dict1={'100':9, '101:9, '102':11, '103':10} #the keys are student ID and the values are the grade level of the student. Alice is 100, Bob=101...
dict2={'100':9721234567, '101':6071234567, '103': 9727654321, '104':6077654321} #this dictionary gives the home phone number as a value using the student ID as a key.
How can I make a master dictionary to give me all of a student's information? Here's what I've tried based on reading answers to other questions.
Dicta=dict(zip(names, dict1))
Dictb=dict(zip(names, dict2))
Dict=dict(zip(Dicta, Dictb))
Here's the sort of answer I'd like to get.
>Dict[Alice]
>>>'100, 9, 9721234567'
#this is Alice's ID, grade level, and home phone

names is ordered, but the keys of a dict are unordered, so you can't rely on zip(names,dict1) to correctly match names with keys (student ID). For example:
>>> d = {'100':1,'101':2,'102':3,'103':4}
>>> d
{'102': 3, '103': 4, '100': 1, '101': 2} # keys not in order declared.
You need one more dict matching names to student ID. Below I've added an ordered list of IDs then create that dictionary. Then I use a dict comprehension to compute the combined dictionary.
names = ['Alice','Bob','Charles','Dan']
ids = ['100','101','102','103']
dictn = dict(zip(names,ids))
dict1={'100':9, '101':9, '102':11, '103':10}
dict2={'100':9721234567, '101':6071234567, '102': 9727654321, '103':6077654321}
Dict = {k:(v,dict1[v],dict2[v]) for k,v in dictn.items()}
print Dict
print Dict['Alice']
Output:
{'Bob': ('101', 9, 6071234567L), 'Charles': ('102', 11, 9727654321L), 'Alice': ('100', 9, 9721234567L), 'Dan': ('103', 10, 6077654321L)}
('100', 9, 9721234567L)

Related

How do I aggregate values in a python list or dictionary based on book title?

Currently, my data is like this or a dictionary, not aggregated by title:
{Great Expectations, Bookstore 1, $8.99},
{Great Expectations, Bookstore 2, $12.99},
{Great Expectations, Bookstore 3, $6.99},
{Tales from the Crypt, Bookstore 1, $5.99},
{The Sisterhood of the Traveling Pants, Bookstore 3, $8.99}
{Oprah: The Icon, Bookstore 2, $6.99}
{Oprah: The Icon, Bookstore 3, $9.99}
I'd like to create list of a dictionary of prices that's aggregated by title that looks like this:
[Great Expectations, {price1: $6.99, price2: $8.99, price3: $12.99}],
[Tales from the Crypt, {price1: $5.99}],
[The Sisterhood of the.., {price1: $6.99}],
[Oprah: The Icon, {price1: $6.99, price2: $9.99}]
Thanks for your help. I will eventually pass this data into a Django view as a list. There can be more than 3 prices, n prices. I'd also like to order the prices from smallest to largest.
Assuming your initial list of books will follow a standard pattern of the first element being the title, second the bookstore and third price, you could do something like this:
aggregrated_books = {}
for book in book_list:
if aggregrated_books[book[0]]:
aggregrated_books[book[0]].append(book[2])
else:
aggregrated_books[book[0]] = [book[2]]
This will output something like:
{'Great Expectations': [6.99, 8.99, 12.99],
'Tales from the Crypt': [5.99],
'The Sisterhood of the', [6.99],
'Oprah: The Icon', [6.99, 9.99]}
Depending on what your use case for this data is you'd be better off aggregating to a list of prices rather than a dictionary like you included in your question. You can easily add price1 price2 etc when iterating through the list later.

Looping through a list (with sublists) and assign the matching IDs to the same key and all of the corresponding values from that sublist?

I'm quite new in python coding and I canĀ“t solve the following problem:
I have a list with trackingpoints for different animals(ID,date,time,lat,lon) given in strings:
aList = [[id,date,time,lat,lon],
[id2,date,time,lat,lon],
[...]]
The txt file is very big and the IDs(a unique animal) is occuring multiple times:
i.e:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421],
['25','20-05-13','15:18:15','34.89932','24.13421'],
[...]]
What I'm trying to do is order the ID's in dictionaries so each unique ID will be the key and all the dates, times, latitudes and longitudes will be the values. Then I would like to write each individual ID to a new txt file so all the values for a specific ID are in one txt file. The output should look like this:
{'25':['20-05-13','15:16:17','34.89932','24.09421'],
['20-05-13','15:18:15','34.89932','24.13421'],
[...],
'24':['20-05-13','15:16:18','35.89932','23.09421'],
[...]
}
I have tried the following (and a lot of other solutions which didn't work):
items = {}
for line in aList:
key,value = lines[0],lines[1:]
items[key] = value
Which results in a key with the last value in the list forthat particular key :
{'25':['20-05-13','15:18:15','34.89932','24.13421'],
'24':['20-05-13','15:16:18','35.89932','23.09421']}
How can I loop through my list and assign the same IDs to the same key and all the corresponding values?
Is there any simple solution to this? Other "easier to implement" solutions are welcome!
I hope it makes sense :)
Try adding all the lists that match to the same ID as list of lists:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421'],
['25','20-05-13','15:18:15','34.89932','24.13421'],
]
items = {}
for line in aList:
key,value = line[0],line[1:]
if key in items:
items[key].append(value)
else:
items[key] = [value]
print items
OUTPUT:
{'24': [['20-05-13', '15:16:18', '35.89932', '23.09421']], '25': [['20-05-13', '15:16:17', '34.89932', '24.09421'], ['20-05-13', '15:18:15', '34.89932', '24.13421']]}

Python3: Checking if a key word within a dictionary matches any part of a string

I'm having trouble converting my working code from lists to dictionaries. The basics of the code checks a file name for any keywords within the list.
But I'm having a tough time understanding dictionaries to convert it. I am trying to pull the name of each key and compare it to the file name like I did with lists and tuples. Here is a mock version of what i was doing.
fname = "../crazyfdsfd/fds/ss/rabbit.txt"
hollow = "SFV"
blank = "2008"
empty = "bender"
# things is list
things = ["sheep", "goat", "rabbit"]
# other is tuple
other = ("sheep", "goat", "rabbit")
#stuff is dictionary
stuff = {"sheep": 2, "goat": 5, "rabbit": 6}
try:
print(type(things), "things")
for i in things:
if i in fname:
hollow = str(i)
print(hollow)
if hollow == things[2]:
print("PERFECT")
except:
print("c-c-c-combo breaker")
print("\n \n")
try:
print(type(other), "other")
for i in other:
if i in fname:
blank = str(i)
print(blank)
if blank == other[2]:
print("Yes. You. Can.")
except:
print("THANKS OBAMA")
print("\n \n")
try:
print(type(stuff), "stuff")
for i in stuff: # problem loop
if i in fname:
empty = str(i)
print(empty)
if empty == stuff[2]: # problem line
print("Shut up and take my money!")
except:
print("CURSE YOU ZOIDBERG!")
I am able to get a full run though the first two examples, but I cannot get the dictionary to run without its exception. The loop is not converting empty into stuff[2]'s value. Leaving money regrettably in fry's pocket. Let me know if my example isn't clear enough for what I am asking. The dictionary is just short cutting counting lists and adding files to other variables.
A dictionary is an unordered collection that maps keys to values. If you define stuff to be:
stuff = {"sheep": 2, "goat": 5, "rabbit": 6}
You can refer to its elements with:
stuff['sheep'], stuff['goat'], stuff['rabbit']
stuff[2] will result in a KeyError, because the key 2 is not found in your dictionary. You can't compare a string with the last or 3rd value of a dictionary, because the dictionary is not stored in an ordered sequence (the internal ordering is based on hashing). Use a list or tuple for an ordered sequence - if you need to compare to the last item.
If you want to traverse a dictionary, you can use this as a template:
for k, v in stuff.items():
if k == 'rabbit':
# do something - k will be 'rabbit' and v will be 6
If you want to check to check the keys in a dictionary to see if they match part of a string:
for k in stuff.keys():
if k in fname:
print('found', k)
Some other notes:
The KeyError would be much easier to notice... if you took out your try/except blocks. Hiding python errors from end-users can be useful. Hiding that information from YOU is a bad idea - especially when you're debugging an initial pass at code.
You can compare to the last item in a list or tuple with:
if hollow == things[-1]:
if that is what you're trying to do.
In your last loop: empty == str(i) needs to be empty = str(i).

Sort nested dictionary in ascending order and grab outer key?

I have a dictionary that looks like:
dictionary = {'article1.txt': {'harry': 3, 'hermione': 2, 'ron': 1},
'article2.txt': {'dumbledore': 1, 'hermione': 3},
'article3.txt': {'harry': 5}}
And I'm interested in picking the article with the most number of occurences of Hermione. I already have code that selects the outer keys (article1.txt, article2.txt) and inner key hermione.
Now I want to be able to have code that sorts the dictionary into a list of ascending order for the highest number occurrences of the word hermione. In this case, I want a list such that ['article1.txt', 'article2.txt']. I tried it with the following code:
#these keys are generated from another part of the program
keys1 = ['article1.txt', 'article2.txt']
keys2 = ['hermione', 'hermione']
place = 0
for i in range(len(keys1)-1):
for j in range(len(keys2)-1):
if articles[keys1[i]][keys2[j]] > articles[keys1[i+1]][keys2[j+1]]:
ordered_articles.append(keys1[i])
place += 1
else:
ordered_articles.append(place, keys1[i])
But obviously (I'm realizing now) it doesn't make sense to iterate through the keys to check if dictionary[key] > dictionary[next_key]. This is because we would never be able to compare things not in sequence, like dictionary[key[1]] > dictionary[key[3]].
Help would be much appreciated!
It seems that what you're trying to do is sort the articles by the amount of 'hermiones' in them. And, python has a built-in function that does exactly that (you can check it here). You can use it to sort the dictionary keys by the amount of hermiones each of them points to.
Here's a code you can use as example:
# filters out articles without hermione from the dictionary
# value here is the inner dict (for example: {'harry': 5})
dictionary = {key: value for key, value in dictionary.items() if 'hermione' in value}
# this function just returns the amount of hermiones in an article
# it will be used for sorting
def hermione_count(key):
return dictionary[key]['hermione']
# dictionary.keys() is a list of the keys of the dictionary (the articles)
# key=... here means we use hermione_count as the function to sort the list
article_list = sorted(dictionary.keys(), key=hermione_count)

Iterating over dictionaries in order and printing the values [duplicate]

This question already has answers here:
How to keep keys/values in same order as declared?
(13 answers)
Closed 8 years ago.
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
for key in stock:
print key
print 'prince: %s' % prices[key]
print 'stock: %s' % stock[key]
The output when I run this code is as follows:
orange
prince: 1.5
stock: 32
pear
prince: 3
stock: 15
banana
prince: 4
stock: 6
apple
prince: 2
stock: 0
Why is it not printing according the order in which the elements appear in the dictionary? For example, why isn't 'banana' printed first, as follows:
banana
price: 4
stock: 6
Python dictionaries are unordered, meaning they won't remember the order you put elements in. This post has some answers that may be helpful to you if you are looking for more information on dictionaries.
You can create an ordered dictionary-equivalent using the OrderedDict datatype.
Dictionaries don't have an order. The point of a dictionary is to fetch items by a key which is provided by the programmer, so it doesn't make sense to maintain order; as long as it is quick and easy to fetch items by their key.
There is OrderedDict which will remember the order in which the keys were inserted.
For your case, it is better to rearrange your data:
stock = {'banana': {'price': 4, 'stock': 6}, 'apple': {'price': 2, 'stock': 0}}
for fruit, details in stock.iteritems():
print('{0}'.format(fruit))
print('Price: {0.price}'.format(details))
print('Stock: {0.stock}'.format(details))
You can also just use tuple, like this:
stock = {'banana': (4, 6), 'apple': (2, 0)}
for fruit, details in stock.iteritems():
price, stock = details
print('{0}'.format(fruit))
print('Price: {0}'.format(price))
print('Stock: {0}'.format(stock))
Dictionaries are an unordered set of key:value pairs. They have no notion of order.
You can check out OrderedDict if you would like an ordered dictionary. Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
See: https://docs.python.org/2/library/collections.html
collections.OrderedDict