I am new to Python. Suppose you have python dictionary, where values are lists different elements. These values can contain only integers, only strings or both. I need to find values that contain both strings and integers.
This is my solution, which works but is not very elegant.
for key,value in dict.iteritems():
int_count=0
len_val=len(value)
for v in value:
if v.isdigit():
int_coun+=1
if (int_count!=0 and int_count<len_chr):
print value
I wonder if it is conceptually possible to do something like this regex:
if [0-9].* and [a-z,A-Z].* in value:
print value
or in other effective and elegant way.
Thanks
EDIT
Here is an example of dictionary:
dict={ 'D00733' : ['III', 'I', 'II', 'I', 'I']
'D00734' : ['I', 'IV', '78']
'D00735' : ['3', '7', '18']}
What I want is:
['I', 'IV', '78']
Here is a solution that you can try:
import numbers
import decimal
dct = {"key1":["5", "names", 1], "Key2":[4, 5, 3, 5]}
new_dict = {}
new_dict = {a:b for a, b in dct.items() if any(i.isalpha() for i in b) and any(isinstance(i, numbers.Number) for i in b)}
Here is a solution using regex:
import re
dct = {"key1":["5", "names", 1], "Key2":[4, 5, "hi", "56"]}
for a, b in dct.items():
new_list = ''.join(map(str, b))
expression = re.findall(r'[a-zA-Z]', new_list)
expression1 = re.findall(r'[0-9]', new_list)
if len(expression) > 0 and len(expression1) > 0:
new_dict[a] = b
print new_dict
This algorithm builds a new dictionary with the values from the previous dictionary that meet the original criteria.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.