Counting string using for loop - python

I don't know what I am doing wrong. When I input a string it gives me back the letter but only gives the occurrence of 1. Can somebody tell what I am doing wrong.
def printDictionary(a):
c=sorted(a)
for char in c:
print(char, c.count(char))
PS I'm new to python

Seems to work when passed a string:
>>> printDictionary('abcaab')
a 3
a 3
a 3
b 2
b 2
c 1
So I assume that you are passing dictionaries to printDictionary() (only seems logical)...
The line
c=sorted(a)
assigns to c the sorted keys of the dictionary a. Since dictionary keys are unique there can only ever be one instance of that key in a dictionary, hence c.count(char) always returns 1.
>>> printDictionary(dict(a=1,b=10,zz=22,ABC=1033))
ABC 1
a 1
b 1
zz 1

Suppose you have this dictionary:
{'a': ['ant', 'abacus'], 'b': ['bear']}
And you want to get this output:
a 2
b 1
Then use this function:
def printDictionary(dictionary):
keys = sorted(dictionary)
for key in keys:
print(key, len(dictionary[key]))

Related

Use values of a list as keys while adding other lists as values for each of the keys

I have 3 lists. I want to use the first that has 2 values as keys to a dictionary while adding the other 2 lists as values for each of the keys.
a = ['1','2']
b = ['3','4','5']
c = ['6','7','8']
expected result:
d = {1:['3','4','5'],2:['6','7','8']}
I've tried some combinations of dict(zip()) but wasn't able to achieve it. Thank you for any help.
By using zip(...) you can get the output you're looking for, but you'll need to create a list with b and c.
a, b, c = ['1','2'], ['3','4','5'], ['6','7','8']
d = dict(zip(a, (b,c)))
print(d)

How to find the numbers connected with a number?

Suppose we have two inputs a and b where a denotes the first integer and b denotes the second integer
for example :
if
a= 1 b = 2
a=1 b=3
a=2 b=3
here 1 is connected with two integers 2 and 3 and 2 is connected with one integer 3
how I can find this and print the result like this {1:{2,3}, 2:{3}}
Note: a is basically the first integer and b is the integer connected with a
Thanks in advance. and this is not homework.
You can have a function like this:
d = {}
def connect(a,b):
if a not in d:
d[a] = [b]
else:
d[a].append(b)
connect(1,2)
connect(1,3)
connect(2,3)
print(d)
output:
{1: [2, 3], 2: [3]}
If 'a' is already in the dictionary, it will add 'b' to the list connected to it. and otherwise a new item will be added to dictionary with 'a' as key and list with 'b' in it as value.
You need a data structure that is called a map, however in Python it is also called a dictionary.
A map stores entries consisting of one key and one value each.
As you want to store potentially multiple values for each key, you can use lists of int as values for your map.
Alternatively you can also use a multi map, however it is not part of the default Python library but there are additional libraries with this functionality.

Python defaultdict

I found something strange that I couldn't understand.
This is the case:
from collections import defaultdict
a = defaultdict(lambda: len(a))
This is just the part of the code, and the code has never defined 'a' above.
The questions are:
Is it possible to use defaultdict as is, not specifying the variable previously?
If possible, what is the meaning of that code?
Maybe it is best explained in an example:
>>> a = defaultdict(lambda: len(b))
>>> b = 'abcd'
>>> a[0]
4
As you can see, it is possible to use b in the lambda even though the b does not yet exist at that point. What is important is that b exists at the time when the lambda is executed. At that point, Python will look for a variable named b and use it.
Note also that the original code does not necessarily use length of the defaultdict itself. It simply evaluates whatever a is at that point. See this example:
>>> a = defaultdict(lambda: len(a))
>>> a['a']
0
>>> a['b']
1
So far, so good. But then rename some things:
>>> x = a
>>> a = []
>>> x['c']
0
>>> x['d']
0
Now the deaultdict is named x, but it does not use len(x). It still uses len(a). This caveat may become important if you sent the defaultdict to a function where a does not mean anything.
you are saying to default dict, when i try to do something with a key and it doesnt exist, use this lambda as the inital value for the key. since your lambda is using a (i.E the dict its self) and you say the length of it. It means when you perform operations using a key thats not in the dict then the dict will use the lambda instead or in this case the length of the dict as the value
from collections import defaultdict
a = defaultdict(lambda: len(a))
a['one'] += 5 #here dict length is 0 so value is 0 + 5 = 5
a['two'] += 2 #jere dict length is 1 so value is 1 + 2 = 3
a['three'] += 1 #here dict length is 2 so value is 2 + 1 = 3
print(a.items())
print(a['newval']) #here newval doesnt exist so will use default value which is length of dict I.E 3
OUTPUT
dict_items([('one', 5), ('two', 3), ('three', 3)])
3
Here's how defaultdict works. Say you have a dict of lists and you're setting values for keys that might not exist. In that case you'd do something like this:
d = dict()
if some_key not in d:
d[some_key] = list()
d[some_key].append(some_value)
defaultdict does this automatically for you by passing it a callable, e.g., int, list, set, which will call int() (default value 0), list() (default value empty list), and set() (default value empty set) respectively. Your lambda is also a callable, which returns integers, so you'll have a dict with int values. But the value you get from the expression will depend on the size of the dict.
Can you do a = defaultdict(lambda: len(a))?
Yes, you can. The lambda will not be executed until called which is when it'll look up the name a. Compare these two cases.
f = lambda: len(a)
a = defaultdict(f)
a[0] # this is when the lambda is called for the first time
But,
g = lambda: len(b)
g() # this will raise a NameError
b = defauldict(g)

Executing join of dictionary of list items

I have a dictionary of the form dict[keyA][key1] where 'key1' is a dictionary of lists. i.e., keyA is a dictionary of dictionaries of lists. Below is a sample of how the dictionary could be created.
dict = { 'keyA': { 'keyA1': ['L1','L2',...], 'keyA2': ['L','L',...], ... },
'keyB': { 'keyB1': ['L1','L2',...], 'key...': ['L','L',..], ...}
}
I need to join the values of the lists together and would like to do this with a construct like:
newStr = ' A B C '.join(val for val in (dict[keyA][k] for k in dict[keyA]))
This fails with an error that val is a 'list' vs. a string.
when I resolve val via 2 for loops I get a list of strings as I would expect the above to provide.
Simple example that works for a one entry in the outer dictionary and prints a list of strings
for k in dict[keyA]:
for val in dict[keyA][k]:
print(val)
Example that does not work and prints a 'list':
for val in (dict[keyA][k] for k in dict[keyA]): print(val)
output from failing test above (note the enclosing brackets in the output). If I 'type' this value, it indicates that the value is indeed a list:
['some text', 'some more text', ....]
The working nested 'for' loops above produces the above text on separate lines without the brackets as expected, the output of which should work in the join to give the desired results....
Can anyone explain what I am missing here?
Your syntax for the "nested" comprehension isn't quite correct.
If you separate out the second portion, you'll see what's tripping it up:
>>> [_dict['keyA'][k] for k in _dict['keyA']]
[['L1', 'L2', 'L3'], ['Q1', 'Q2', 'Q3']]
The order for a nested comprehension isn't intuitive (IMO) and reads left-to-right in order of descending loops, instead of in an unrolling fashion which I think most people would initially assume.
In any case, you just need to adjust your comprehension:
>>> ' A B C '.join(val for key in _dict['keyA'] for val in _dict['keyA'][key])
'L1 A B C L2 A B C L3 A B C Q1 A B C Q2 A B C Q3'
Or using dict.items:
(Note: _ is used as a placeholder/throwaway here, since you don't actually need the "key" loop variable in this case)
>>> ' A B C '.join(val for _, v in _dict['keyA'].items() for val in v)
'L1 A B C L2 A B C L3 A B C Q1 A B C Q2 A B C Q3'
Also, as an aside, avoid using python built-ins as variable names, or you won't be able to use that built-in later on in your code.

Can't get function to add an item to a dictionnary [duplicate]

This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
I wanted to test if a key exists in a dictionary before updating the value for the key.
I wrote the following code:
if 'key1' in dict.keys():
print "blah"
else:
print "boo"
I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?
in tests for the existence of a key in a dict:
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
Use dict.get() to provide a default value when the key does not exist:
d = {}
for i in range(10):
d[i] = d.get(i, 0) + 1
To provide a default value for every key, either use dict.setdefault() on each assignment:
d = {}
for i in range(10):
d[i] = d.setdefault(i, 0) + 1
or use defaultdict from the collections module:
from collections import defaultdict
d = defaultdict(int)
for i in range(10):
d[i] += 1
Use key in my_dict directly instead of key in my_dict.keys():
if 'key1' in my_dict:
print("blah")
else:
print("boo")
That will be much faster as it uses the dictionary's O(1) hashing as opposed to doing an O(n) linear search on a list of keys.
You can test for the presence of a key in a dictionary, using the in keyword:
d = {'a': 1, 'b': 2}
'a' in d # <== evaluates to True
'c' in d # <== evaluates to False
A common use for checking the existence of a key in a dictionary before mutating it is to default-initialize the value (e.g. if your values are lists, for example, and you want to ensure that there is an empty list to which you can append when inserting the first value for a key). In cases such as those, you may find the collections.defaultdict() type to be of interest.
In older code, you may also find some uses of has_key(), a deprecated method for checking the existence of keys in dictionaries (just use key_name in dict_name, instead).
You can shorten your code to this:
if 'key1' in my_dict:
...
However, this is at best a cosmetic improvement. Why do you believe this is not the best way?
For additional information on speed execution of the accepted answer's proposed methods (10 million loops):
'key' in mydict elapsed time 1.07 seconds
mydict.get('key') elapsed time 1.84 seconds
mydefaultdict['key'] elapsed time 1.07 seconds
Therefore using in or defaultdict are recommended against get.
I would recommend using the setdefault method instead. It sounds like it will do everything you want.
>>> d = {'foo':'bar'}
>>> q = d.setdefault('foo','baz') #Do not override the existing key
>>> print q #The value takes what was originally in the dictionary
bar
>>> print d
{'foo': 'bar'}
>>> r = d.setdefault('baz',18) #baz was never in the dictionary
>>> print r #Now r has the value supplied above
18
>>> print d #The dictionary's been updated
{'foo': 'bar', 'baz': 18}
A dictionary in Python has a get('key', default) method. So you can just set a default value in case there isn't any key.
values = {...}
myValue = values.get('Key', None)
Using the Python ternary operator:
message = "blah" if 'key1' in my_dict else "booh"
print(message)
Use EAFP (easier to ask forgiveness than permission):
try:
blah = dict["mykey"]
# key exists in dict
except KeyError:
# key doesn't exist in dict
See other Stack Overflow posts:
Using 'try' vs. 'if' in Python
Checking for member existence in Python
Check if a given key already exists in a dictionary
To get the idea how to do that we first inspect what methods we can call on dictionary.
Here are the methods:
d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Python Dictionary clear() Removes all Items
Python Dictionary copy() Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys() Creates dictionary from given sequence
Python Dictionary get() Returns Value of The Key
Python Dictionary items() Returns view of dictionary (key, value) pair
Python Dictionary keys() Returns View Object of All Keys
Python Dictionary pop() Removes and returns element having given key
Python Dictionary popitem() Returns & Removes Element From Dictionary
Python Dictionary setdefault() Inserts Key With a Value if Key is not Present
Python Dictionary update() Updates the Dictionary
Python Dictionary values() Returns view of all values in dictionary
The brutal method to check if the key already exists may be the get() method:
d.get("key")
The other two interesting methods items() and keys() sounds like too much of work. So let's examine if get() is the right method for us. We have our dict d:
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}
Printing shows the key we don't have will return None:
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1
We use that to get the information if the key is present or no.
But consider this if we create a dict with a single key:None:
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None
Leading that get() method is not reliable in case some values may be None.
This story should have a happier ending. If we use the in comparator:
print('key' in d) #True
print('key2' in d) #False
We get the correct results.
We may examine the Python byte code:
import dis
dis.dis("'key' in d")
# 1 0 LOAD_CONST 0 ('key')
# 2 LOAD_NAME 0 (d)
# 4 COMPARE_OP 6 (in)
# 6 RETURN_VALUE
dis.dis("d.get('key2')")
# 1 0 LOAD_NAME 0 (d)
# 2 LOAD_METHOD 1 (get)
# 4 LOAD_CONST 0 ('key2')
# 6 CALL_METHOD 1
# 8 RETURN_VALUE
This shows that in compare operator is not just more reliable, but even faster than get().
The ways in which you can get the results are:
if your_dict.has_key(key) Removed in Python 3
if key in your_dict
try/except block
Which is better is dependent on 3 things:
Does the dictionary 'normally has the key' or 'normally does not have the key'.
Do you intend to use conditions like if...else...elseif...else?
How big is dictionary?
Read More: http://paltman.com/try-except-performance-in-python-a-simple-test/
Use of try/block instead of 'in' or 'if':
try:
my_dict_of_items[key_i_want_to_check]
except KeyError:
# Do the operation you wanted to do for "key not present in dict".
else:
# Do the operation you wanted to do with "key present in dict."
Python 2 only: (and Python 2.7 supports `in` already)
You can use the has_key() method:
if dict.has_key('xyz')==1:
# Update the value for the key
else:
pass
Just an FYI adding to Chris. B's (best) answer:
d = defaultdict(int)
Works as well; the reason is that calling int() returns 0 which is what defaultdict does behind the scenes (when constructing a dictionary), hence the name "Factory Function" in the documentation.
A Python dictionary has the method called __contains__. This method will return True if the dictionary has the key, else it returns False.
>>> temp = {}
>>> help(temp.__contains__)
Help on built-in function __contains__:
__contains__(key, /) method of builtins.dict instance
True if D has a key k, else False.
Another way of checking if a key exists using Boolean operators:
d = {'a': 1, 'b':2}
keys = 'abcd'
for k in keys:
x = (k in d and 'blah') or 'boo'
print(x)
This returns
>>> blah
>>> blah
>>> boo
>>> boo
Explanation
First, you should know that in Python, 0, None, or objects with zero length evaluate to False. Everything else evaluates to True. Boolean operations are evaluated left to right and return the operand not True or False.
Let's see an example:
>>> 'Some string' or 1/0
'Some string'
>>>
Since 'Some string' evaluates to True, the rest of the or is not evaluated and there is no division by zero error raised.
But if we switch the order 1/0 is evaluated first and raises an exception:
>>> 1/0 or 'Some string'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
We can use this for pattern for checking if a key exists.
(k in d and 'blah')
does the same as
if k in d:
'blah'
else:
False
This already returns the correct result if the key exists, but we want it to print 'boo' when it doesn't. So, we take the result and or it with 'boo'
>>> False or 'boo'
'boo'
>>> 'blah' or 'boo'
'blah'
>>>
You can use a for loop to iterate over the dictionary and get the name of key you want to find in the dictionary. After that, check if it exist or not using if condition:
dic = {'first' : 12, 'second' : 123}
for each in dic:
if each == 'second':
print('the key exists and the corresponding value can be updated in the dictionary')

Categories

Resources